2012年(1008)
分类:
2012-08-01 11:08:48
原文地址:虚基类 作者:luozhiyong131
/*
* 虚基类
* 声明了虚基类之后,虚基类的成员在进一步派生过程中和派生类一起维护同一个内存数据拷贝
* Lzy 2011-七夕
*/
#include
using namespace std;
class A
{
protected:
int a;
public:
A():a(50){}
};
class B1:virtual public A
{
protected:
int b1;
public:
B1():b1(60){}
void g(){a=10;cout<<"B1 "<" "<
};
class B2:virtual public A
{
protected:
int b2;
public:
B2():b2(70){}
void g(){a=20;cout<<"B2 "<" "<
};
class C:public B1, public B2
{
protected:
int c;
public:
C():c(80){}
void g(){a=30;b1=40;b2=50;cout<<"C "<" "<
/*虚基类的成员在进一步派生过程中和派生类一起维护同一个内存数据拷贝,
所以a变量只存在唯一的一个,不需使用作用域运算符*/
};
int main()
{
C d1;
/*使用虚基类后,类D对象中只存在一个虚基类A的子对象,所以d1.print()是合法的*/
d1.print();
d1.B1::g();
d1.B2::g();
d1.g();
return 0;
}
/*
* 虚基类的析构函数和构造函数
* Lzy 2011-七夕
*/
#include
using namespace std;
class A
{
protected:
int a;
public:
A():a(50){cout<<"A 缺省构造函数: a="<
A(int i):a(i){cout<<"A 构造函数: a="<
};
class B1:virtual public A
{
protected:
int b1;
public:
B1():b1(60){cout<<"B1 缺省构造函数: b1="<
B1(int i, int j):A(i),b1(j){cout<<"B1 构造函数: b1="<
~B1(){cout<<"B1 析构函数:b1="<
};
class B2:virtual public A
{
protected:
int b2;
public:
B2():b2(70){cout<<"B2 缺省构造函数: b2="<
B2(int i, int j):A(i),b2(j){cout<<"B2 构造函数: b2="<
~B2(){cout<<"B2 析构函数:b2="<
};
class C:public B1, public B2
{
protected:
int c;
public:
C():c(70){cout<<"C 缺省构造函数: c="<
C(int i, int j,int x, int y):A(i),B1(i,j),B2(i,x),c(y){cout<<"C 构造函数: c="<
~C(){cout<<"C 析构函数:c="<
};
int main()
{
C obj1;
{
C obj2(6,7,8,9);
}
return 0;
}
/*
* 无虚基类的析构函数和构造函数
* Lzy 2011-七夕
*/
#include
using namespace std;
class A
{
protected:
int a;
public:
A():a(50){cout<<"A 缺省构造函数: a="<
A(int i):a(i){cout<<"A 构造函数: a="<
};
class B1: public A
{
protected:
int b1;
public:
B1():b1(60){cout<<"B1 缺省构造函数: b1="<
B1(int i, int j):A(i),b1(j){cout<<"B1 构造函数: b1="<
~B1(){cout<<"B1 析构函数:b1="<
};
class B2: public A
{
protected:
int b2;
public:
B2():b2(70){cout<<"B2 缺省构造函数: b2="<
B2(int i, int j):A(i),b2(j){cout<<"B2 构造函数: b2="<
~B2(){cout<<"B2 析构函数:b2="<
};
class C:public B1, public B2
{
protected:
int c;
public:
C():c(70){cout<<"C 缺省构造函数: c="<
C(int i, int j,int x, int y):B1(i,j),B2(i,x),c(y){cout<<"C 构造函数: c="<
~C(){cout<<"C 析构函数:c="<
};
int main()
{
C obj1;
{
C obj2(6,7,8,9);
}
return 0;
}