虚基类:当一个基类被声明为虚基类后,即使它成为了多继承链路上的公共基类,最后的派生类中也只有它的一个备份。
虚基类的特点:
虚基类构造函数的参数必须由最新派生出来的类负责初始化(即使不是直接继承);
虚基类的构造函数先于非虚基类的构造函数执行。
-
#include <iostream>
-
using namespace std;
-
// 虚基类的构造函数在非虚基类的构造函数之前调用
-
// 虚基类的作用是表明这个类是公共继承的,且只有一份
-
class A
-
{
-
protected:
-
int a;
-
public:
-
A():a(50){cout<<"A 缺省构造函数: a="<<a<<endl;}
-
A(int i):a(i){cout<<"A 构造函数: a="<<a<<endl;}
-
~A(){cout<<"A 析构函数:a="<<a<<endl;}
-
};
-
-
class B1:virtual public A
-
{
-
protected:
-
int b1;
-
public:
-
B1():b1(60){cout<<"B1 缺省构造函数: b1="<<b1<<endl;}
-
B1(int i, int j):A(i),b1(j){cout<<"B1 构造函数: b1="<<b1<<endl;}
-
~B1(){cout<<"B1 析构函数:b1="<<b1<<endl;}
-
};
-
-
class B2:virtual public A
-
{
-
protected:
-
int b2;
-
public:
-
B2():b2(70){cout<<"B2 缺省构造函数: b2="<<b2<<endl;}
-
B2(int i, int j):A(i),b2(j){cout<<"B2 构造函数: b2="<<b2<<endl;}
-
~B2(){cout<<"B2 析构函数:b2="<<b2<<endl;}
-
};
-
-
class C:virtual public B1, virtual public B2
-
{
-
protected:
-
int c;
-
public:
-
C():c(70){cout<<"C 缺省构造函数: c="<<c<<endl;}
-
C(int i, int j,int x, int y):A(i),B1(i,j),B2(i,x),c(y){cout<<"C 构造函数: c="<<c<<endl;}
-
~C(){cout<<"C 析构函数:c="<<c<<endl;}
-
};
-
-
int main()
-
{
-
C obj1;
-
C obj2(6,7,8,9);
-
-
return 0;
-
}
阅读(2629) | 评论(0) | 转发(0) |