cpp——与c之不同——struct union

来源:互联网 发布:德川家光 知乎 编辑:程序博客网 时间:2024/06/05 09:41

struct

c

  • struct是不同数据类型的聚集体,通过相对于struct首地址的offset获取struct成员,struct每个成员保存了相对于struct首地址的offset和自身字长

c++

struct等同于class,除了默认成员访问权限和默认继承方式不同
  • class默认成员访问权限为private,默认继承方式为private
  • struct默认成员访问权限为public,默认继承方式为public
class CAnimal{    int food1;    public:    int food2;};struct SAnimal{    int food1;    public:    int food2;};class CDog1 : CAnimal{};class CDog2 : SAnimal{};struct SDog1 : CAnimal{};struct SDog2 : SAnimal{};void member_access_privilege(){    CAnimal c_animal;    SAnimal s_animal;        //c_animal.food1 = 1;  //private    c_animal.food2 = 2;        s_animal.food1 = 1;    s_animal.food2 = 2;        CDog1 c_dog1;    CDog2 c_dog2;        //c_dog1.food1 = 1;  //private    //c_dog1.food2 = 2;  //private        //c_dog2.food1 = 1;  //private    //c_dog2.food2 = 2;  //private        SDog1 s_dog1;    SDog2 s_dog2;        //s_dog1.food1 = 1;  //private    s_dog1.food2 = 2;        s_dog2.food1 = 1;    s_dog2.food2 = 2;}
总结:
  • class默认成员访问权限为private,struct默认成员访问权限为public
  • 子类为class,默认继承方式为private,子类为struct,默认继承方式为public,即默认继承方式决定于子类的class或struct,与父类的class或struct无关
  • c++ struct几乎等同于class,仅仅在于默认成员访问权限和默认继承方式的不同,c++ struct意义已明显不同于c struct,因此c++中应避免使用struct,一概使用class,以免与c struct混淆
  • 应该显式指定成员访问权限和继承方式,避免使用默认成员访问权限和默认继承方法

union

c

  • union是一种特殊的c struct,union是所有成员相对于首地址的offset均为0的c struct

c++

  • union是一种特殊的c++ struct,union是所有成员相对于首地址的offset均为0的c++ struct
注:因为union所有成员相对于首地址的offset均为0,因此union不允许包含vptr指针,因此union不允许包含virtual成员函数
0 0
原创粉丝点击