上一篇虚继承举例:http://10638473.blog.51cto.com/10628473/1964414
本文将A类中的show()函数前加上virtual关键字。
//多重继承 #include <iostream> using namespace std; class A { public: int a; A(int a=0):a(a) { cout<<"A基类A::A()"<<endl; } ~A() { cout<<"A基类A::~A()"<<endl; } virtual void show() { cout<<"A基类A::a="<<a<<endl; } }; class B:virtual public A { protected: int b; public: B(int a=0,int b=0):A(a),b(b) { cout<<"B子类B:B()"<<endl; } ~B() { cout<<"B子类B:~B()"<<endl; } void show() { cout<<"B子类B::b="<<b<<endl; } }; class C:virtual public A { protected: int c; public: C(int a=0,int c=0):A(a),c(c) { cout<<"C子类C::C()"<<endl; } ~C() { cout<<"C子类C::~C()"<<endl; } void show() { cout<<"C子类C::c="<<c<<endl; } }; class D:public B,public C { protected: int d; public: D(int a=0,int b=0,int c=0,int d=0):d(d),B(a,b),C(a,c) { cout<<"D孙子类D::D()"<<endl; } ~D() { cout<<"D孙子类D::~D()"<<endl; } void show() { cout<<"D孙子类D::c="<<d<<endl; } }; void Display(A *p) { p->show(); } int main(int argc, char *argv[]) { A a(1); B b(2,3); C c(4,5); D d(6,7,8,9); A *p; p=&a; p->show(); p=&b; p->show(); p=&c; p->show(); B *q; q=&d; q->show(); return 0; }
可以和上一篇对比一下结果。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。