企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
[TOC] ## 多重继承的先后问题 当前实例是CBase的“孙子”,而“父亲”有2个,每个“父亲”都将“爷爷”复制了一份。如果不指定哪个“父亲”的“父亲”,默认将第一个继承的“父亲”的“父亲”当作“爷爷” <details> <summary>main.cpp</summary> ``` #include <iostream> #include <string> using namespace std; class CBase { public: string id; }; class CDerive1 : public CBase { public: void show1() { cout << "CDerive1: " << id << endl; } }; class CDerive2 : public CBase { public: void show2() { cout << "CDerive2: " << id << endl; } }; class CSon : public CDerive2, public CDerive1 { }; int main() { CSon s; s.CDerive1::id = "CDerive1"; s.CDerive2::id="CDerive2"; s.show1(); // CDerive1 s.show2(); // CDerive2 return 0; } ``` </details> <br/> ## 实例地址的调查 由于2个“父亲”因而复制出2个“爷爷”,2个“爷爷”的地址也不同 ## 虚继承 “虚继承”就是在实例中,基类不管继承多少个,只复制一份。 <details> <summary>main.cpp</summary> ``` #include <iostream> #include <string> using namespace std; class Base { public: string id; }; class A:virtual public Base { public: void show() { cout<< id<<endl; } }; class B:virtual public Base { public: void show() { cout <<id<<endl; } }; class C : public A, public B { }; int main() { C c; c.A::id="a-id"; c.B::id="b-id"; c.A::show(); c.B::show(); cout <<c.id<<endl; /** b-id b-id b-id */ return 0; } ``` </details> <br/>