虚基类的作用

当一个基类被声明为虚基类后,即使它成为了多继承链路上的公共基类,最后的派生类中也只有它的一个备份 虚基类的特点: 虚基类构造函数的参数必须由最新派生出来的类负责初始化(即使不是直接继承); 虚基类的构造函数先于非虚基类的构造函数执行。

#include <iostream> using namespace std; class CBase { protected: int a; public: CBase(int na) { a = na; cout << "CBase constructor" << endl; } ~CBase() { cout << "CBase deconstructor!" << endl; } }; class CDerive1: virtual public CBase { public: CDerive1(int na) : CBase(na) { cout << "CDerive1 constructor" << endl; } ~CDerive1() { cout << "CDerive1 deconstructor" << endl; } int GetA() { return a; } }; class CDerive2: virtual public CBase { public: CDerive2(int na): CBase(na) { cout << "CDerive2 constructor" << endl; } ~CDerive2() { cout << "CDerive2 deconstructor" << endl; } int GetA() { return a; } }; class CDerive12: public CDerive1,public CDerive2 { public: CDerive12(int na1,int na2,int na3): CDerive1(na1), CDerive2(na2), CBase(na3) { cout << "CDerive12 constructor" << endl; } ~CDerive12() { cout << "CDerive12 deconstructor" << endl; } }; void main() { CDerive12 obj(100,200,300); cout << "frome CDerive1: a = " << obj.CDerive1::GetA() << endl; cout << "frome CDerive2: a = " << obj.CDerive2::GetA() << endl << endl; }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值