上一篇虚继承举例: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; }
可以和上一篇对比一下结果。
本文出自 “10628473” 博客,请务必保留此出处http://10638473.blog.51cto.com/10628473/1964418
原文:http://10638473.blog.51cto.com/10628473/1964418