struct关键字是从C语言中继承过来的,class和struct均可定义类,用它们定义类的唯一差别在于默认的成员保护级别和默认的继承保护级别(P57--第57页,2.8--章节2.8;P485,15.2.5):
默认情况下,struct的保护级别为public,而class的保护级别为private。
下面分别就这两种情况进行举例:
例1:默认的成员保护级别
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。相当于如下代码:
struct S_Base {
public:
int foo(int) { return 0; }
int val;
};
class C_Base {
private:
int foo(int) { return 0; }
int val;
};
例2:默认的继承保护级别
struct S_Derived : S_Base {
};
class C_Derived : C_Base {
};
以上两个类相当于:
struct S_Derived : public S_Base {
};
class C_Derived : private C_Base {
};
References:
《C++ Primer中文版第4版》P57, 485
本文详细解析了C++中struct与class的区别,包括默认的成员保护级别和继承保护级别的不同。通过实例展示了默认保护级别的应用,并阐述了类之间的默认继承保护级别的差异。
1万+

被折叠的 条评论
为什么被折叠?



