c++中虚继承
//二义性 #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();报错,这里c类中的有两个print()函数,它们的地位相同 c.Base::print(); c.Sub::print(); return 0; }
射阳网站制作公司哪家好,找成都创新互联!从网页设计、网站建设、微信开发、APP开发、成都响应式网站建设等网站项目制作,到程序开发,运营维护。成都创新互联从2013年创立到现在10年的时间,我们拥有了丰富的建站经验和运维经验,来保证我们的工作的顺利进行。专注于网站建设就选成都创新互联。
//砖石继承,二义性
#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;报错,这样使用会产生二义性 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最终被调用了两次.
虚继承
#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()
虚继承,会共享子类通过虚继承的基类的内存,Mid1调用实例化了一次Base,Mid2构造时,就没有再次
实例化Base,Mid1和Mid2共享基类Base的内存.
虚继承,解决了二义性问题,也节省了内存.
文章标题:c++中虚继承
分享地址:http://pwwzsj.com/article/ihgjdi.html