在C++中,除了以下几点外,struct和class是相同的。
(1)class的成员的默认访问控制是private,而struct的成员的默认访问权限是public。
例如,program 1会编译失败,而program 2可正常运行。
1 // Program 1 2 #include3 4 class Test 5 { 6 int x; // x is private 7 }; 8 9 int main()10 {11 Test t;12 t.x = 20; // compiler error because x is private13 getchar();14 return 0;15 }16 17 // Program 218 #include 19 20 struct Test 21 {22 int x; // x is public23 };24 25 int main()26 {27 Test t;28 t.x = 20; // works fine because x is public29 getchar();30 return 0;31 }
(2)在继承体系中,当struct继承自struct/class时,对于base struct/class的默认访问控制是public。但当class继承自struct/class时,对base struct/class的默认访问控制是private。
例如,program 3会编译失败,而program 4可正常运行。
1 // Program 3 2 #include3 4 class Base 5 { 6 public: 7 int x; 8 }; 9 10 class Derived : Base 11 { 12 }; // is equilalent to class Derived : private Base {}13 14 int main()15 {16 Derived d;17 d.x = 20; // compiler error becuase inheritance is private18 getchar();19 return 0;20 }21 22 // Program 423 #include 24 25 class Base 26 {27 public:28 int x;29 };30 31 struct Derived : Base 32 { 33 }; // is equilalent to struct Derived : public Base {}34 35 int main()36 {37 Derived d;38 d.x = 20; // works fine becuase inheritance is public39 getchar();40 return 0;41 }
总结:
对于struct和class的不同点就在于:默认访问控制不同,struct为public,class为private。
而这个不同体现在两个地方:一是成员的默认访问控制;二是继承体系中对基类的默认访问控制。
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
转载请注明:
2013-11-25 19:52:01