#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里,将会无法被继承(编译可以通过,无法产生实例)。