struct关键字是从C语言中继承过来的,class和struct均可定义类,用它们定义类的唯一差别在于默认的成员保护级别和默认的继承保护级别(P57--第57页,2.8--章节2.8;P485,15.2.5):
默认情况下,struct的保护级别为public,而class的保护级别为private。
下面分别就这两种情况进行举例:
例1:默认的成员保护级别
[cpp] view plaincopyprint?
- struct S_Base {
- int foo(int) { return 0; }
- int val;
- };
- class C_Base {
- int foo(int) { return 0; }
- int val;
- };
以上两个类没有显示地使用访问标号(public, protected, private),类的成员具有默认的保护级别,类S_Base成员的保护级别为public,类C_Base成员的保护级别为private。相当于如下代码:
[cpp] view plaincopyprint?
- struct S_Base {
- public:
- int foo(int) { return 0; }
- int val;
- };
- class C_Base {
- private:
- int foo(int) { return 0; }
- int val;
- };
例2:默认的继承保护级别
[cpp] view plaincopyprint?
- struct S_Derived : S_Base {
- };
- class C_Derived : C_Base {
- };
以上两个类相当于:
[cpp] view plaincopyprint?
- struct S_Derived : public S_Base {
- };
- class C_Derived : private C_Base {
- };
References:
《C++ Primer中文版第4版》P57, 485
时间: 2024-08-01 20:44:49