您好,登錄后才能下訂單哦!
//二義性 #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()函數,它們的地位相同 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;報錯,這樣使用會產生二義性 d.Mid1::print();//ok d.Mid2::print();//ok return 0; }
Base::Base()1
Mid1::Mid1()
Base::Base()2
Mid2::Mid2()
Child::Child()
在實例化,Child對象時,先會調用Mid1和Mid2構造函數,Mid1和Mid2分別繼承與Base,所以
Base最終被調用了兩次.
虛繼承
#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()
虛繼承,會共享子類通過虛繼承的基類的內存,Mid1調用實例化了一次Base,Mid2構造時,就沒有再次
實例化Base,Mid1和Mid2共享基類Base的內存.
虛繼承,解決了二義性問題,也節省了內存.
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。