您好,登錄后才能下訂單哦!
//二義性 #include <iostream> using namespace std; class Base{ public: Base(){ cout << "Base called..." << endl; } void print() { cout << "Base ::print()" << endl; } }; class Sub{ public: Sub(){ cout << "Sub called..." << endl; } void print(){ cout << "Sub print...." << endl; } }; class Child: public Base, public Sub{ public: Child(){ cout << "Child called..." << endl; } }; int main(void){ Child c; //c.print();報錯,這里c類中的有兩個print()函數(shù),它們的地位相同 c.Base::print(); c.Sub::print(); return 0; }
//磚石繼承,二義性
#include <iostream> using namespace std; int gFlag = 0; class Base{ public: Base(){ cout << "Base::Base()" <<++gFlag << endl; } void print(){ cout << "Base::print()" << endl; } }; class Mid1:public Base{ public: Mid1(){ cout << "Mid1:Mid1()" << endl; } }; class Mid2:public Base{ public: Mid2(){ cout << "Mid2:Mid2()" << endl; } }; class Child:public Mid1,public Mid2{ public: Child(){ cout << "Child:Child()" << endl; } }; int main(void){ Child d; //d.print() << endl;報錯,這樣使用會產(chǎn)生二義性 d.Mid1::print();//ok d.Mid2::print();//ok return 0; }
Base::Base()1
Mid1::Mid1()
Base::Base()2
Mid2::Mid2()
Child::Child()
在實(shí)例化,Child對象時,先會調(diào)用Mid1和Mid2構(gòu)造函數(shù),Mid1和Mid2分別繼承與Base,所以
Base最終被調(diào)用了兩次.
虛繼承
#include <iostream> using namespace std; int gFlag = 0; class Base{ public: Base(){ cout << "Base::Base()"<<++gFlag << endl; } void print(){ cout << "Base::print()" << endl; } }; class Mid1:virtual public Base{ public: Mid1(){ cout << "Mid1::Mid1()" << endl; } }; class Mid2:virtual public Base{ public: Mid2(){ cout << "Mid2::Mid2()" << endl; } }; class Child:public Mid1,public Mid2{ public: Child(){ cout << "Child::Child()" << endl; } }; int main(void){ Child d; d.print(); return 0; }
Base::Base()1
Mid1::Mid1()
Mid2::Mid2()
Child::Child()
Base::print()
虛繼承,會共享子類通過虛繼承的基類的內(nèi)存,Mid1調(diào)用實(shí)例化了一次Base,Mid2構(gòu)造時,就沒有再次
實(shí)例化Base,Mid1和Mid2共享基類Base的內(nèi)存.
虛繼承,解決了二義性問題,也節(jié)省了內(nèi)存.
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。