关于虚拟继承(1)

#include <iostream>
#include <cmath>
#include <vector>

class D
{
public:
	D() { cout << "D()" << endl; }
	~D() { cout << "~D()" << endl; }
protected:
	int d;
};

class B :virtual public D
{
public:
	B() { cout << "B()" << endl; }
	~B() { cout << "~B()" << endl; }
protected:
	int b;
};


class C :virtual public B
{
public:
	C() { cout << "C()" << endl; }
	~C() { cout << "~C()" << endl; }
protected:
	int c;
};

class A :virtual public B,virtual public C
{
public:
	A() { cout << "A()" << endl; }
	~A() { cout << "~A()" << endl; }
protected:
	int c;
};

class AA :virtual public B,virtual public C
{
public:
	AA() { cout << "AA()" << endl; }
	~AA() { cout << "~AA()" << endl; }
protected:
	int c;
};

int main(){
    D d;
	B b;
	C c;
	Aa a;
	cout << "size of D\t" << sizeof(d) << endl;
	cout << "size of B\t" << sizeof(b) << endl;
	cout << "size of C\t" << sizeof(c) << endl;
	cout << "size of Aa\t" << sizeof(a) << endl;
}

这里在我们使用sizeof函数显示每一种类的大小的时候,会显示

使用virtual继承时在普通的继承的基础上会添加一个vbptr指针(虚基类的指针),因此比普通继承多2字节的大小

 

 

如果某个类的构造函数定义在private里,将会无法被继承(编译可以通过,无法产生实例)。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值