//二義性 #includeusing 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();報(bào)錯(cuò),這里c類中的有兩個(gè)print()函數(shù),它們的地位相同 c.Base::print(); c.Sub::print(); return 0; }
射陽網(wǎng)站制作公司哪家好,找成都創(chuàng)新互聯(lián)!從網(wǎng)頁設(shè)計(jì)、網(wǎng)站建設(shè)、微信開發(fā)、APP開發(fā)、成都響應(yīng)式網(wǎng)站建設(shè)等網(wǎng)站項(xiàng)目制作,到程序開發(fā),運(yùn)營維護(hù)。成都創(chuàng)新互聯(lián)從2013年創(chuàng)立到現(xiàn)在10年的時(shí)間,我們擁有了豐富的建站經(jīng)驗(yàn)和運(yùn)維經(jīng)驗(yàn),來保證我們的工作的順利進(jìn)行。專注于網(wǎng)站建設(shè)就選成都創(chuàng)新互聯(lián)。
//磚石繼承,二義性
#includeusing 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;報(bào)錯(cuò),這樣使用會產(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對象時(shí),先會調(diào)用Mid1和Mid2構(gòu)造函數(shù),Mid1和Mid2分別繼承與Base,所以
Base最終被調(diào)用了兩次.
虛繼承
#includeusing 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í),就沒有再次
實(shí)例化Base,Mid1和Mid2共享基類Base的內(nèi)存.
虛繼承,解決了二義性問題,也節(jié)省了內(nèi)存.