标签:安全 避免 aaa end 多重继承 length 相同 sof rtu
1.构造顺序:按继承顺序,先继承的先构造,同样遵循先构造父类,再构造子类的规则。
2.析构顺序,与构造顺序相反。
3.内存分布:按继承顺序,先继承的分布在前,同样遵循先构造父类,再构造子类的规则。
class Sofa { public: Sofa() { cout << "Sofa()" << endl; } void Sit() { cout << "Sofa Sit" << endl; } int length = 0xaaaaaaaa; int color = 1; }; class Bed { public: Bed() { cout << "Bed()" << endl; } void Sleep() { cout << "Bed Sleep" << endl; } int width = 0xbbbbbbbb; int color = 2; }; class SofaBed : public Sofa, public Bed { public: SofaBed() { cout << "SofaBed()" << endl; } int height = 0xdddddddd; }; int main() { SofaBed sb; sb.Sit(); sb.Sleep(); Sofa *pSofa = &sb; pSofa->length = 1; Bed *pBed = &sb;//安全,指针会定位到Bed数据开始的地址 pBed->width = 2; //sb.color = 3;// error C2385: 对“color”的访问不明确 sb.Sofa::color = 3;//指明是哪个作用域 return 0; }
菱形继承(钻石继承)
问题:两个父类分别从祖宗类继承了一份数据,子类从两个父类继承,则子类有两份祖宗类的数据。
虚继承:解决菱形继承的问题,继承时添加virtual关键字,使相同的祖宗类成员在内存中只有一份。
虚继承时构造顺序:先构造祖宗类,再按继承顺序构造父类,最后构造孙类。
虚继承时析构顺序:与构造顺序相反。
注意:避免使用菱形继承,结构复杂且效率低下。
class Furniture { public: int color = 1; }; class Sofa : virtual public Furniture {//虚继承,继承时添加virtual关键字 public: Sofa() { cout << "Sofa()" << endl; } void Sit() { cout << "Sofa Sit" << endl; } int length = 0xaaaaaaaa; }; class Bed : virtual public Furniture {//虚继承,继承时添加virtual关键字 public: Bed() { cout << "Bed()" << endl; } void Sleep() { cout << "Bed Sleep" << endl; } int width = 0xbbbbbbbb; }; class SofaBed : public Sofa, public Bed { public: SofaBed() { cout << "SofaBed()" << endl; } int height = 0xdddddddd; }; int main() { SofaBed sb; sb.Sit(); sb.Sleep(); Sofa *pSofa = &sb; pSofa->length = 1; Bed *pBed = &sb;//安全,指针会定位到Bed数据开始的地址 pBed->width = 2; sb.color = 3;//由于虚继承,SofaBed中只有一份color了 return 0; }
标签:安全 避免 aaa end 多重继承 length 相同 sof rtu
原文地址:https://www.cnblogs.com/Nutshelln/p/12934968.html