虚基类
时间:2010-06-12 来源:chinawanglun
虚基类
该文基础知识可参见“C++学习笔记(10)——虚基类的作用” 当一个基类被声明为虚基类后,即使它成为了多继承链路上的公共基类,最后的派生类中也只有它的一个备份。例如:class CBase { };
class CDerive1:virtual public CBase{ };
class CDerive2:virtual public CBase{ };
class CDerive12:public CDerive1,CDerive2{ };
则在类CDerive12的对象中,仅有类CBase的一个对象数据
虚基类的特点:
虚基类构造函数的参数必须由最新派生出来的类负责初始化(即使不是直接继承);
虚基类的构造函数先于非虚基类的构造函数执行。 代码如下:
/**//************************************************************************
* 虚继承构造函数的调用顺序
************************************************************************/
#include<iostream.h>
#include <stdio.h>
class A
...{
public:
A(char *s)
...{
cout<<s<<endl;
}
~A()...{cout<<"A destruction!"<<endl;}
};
class B:virtual public A
...{
public:
B(char *s1,char *s2):A(s1)
...{
cout<<s2<<endl;
}
~B()...{cout<<"B destruction!"<<endl;}
};
class C:virtual public A
...{
public:
C(char *s1,char *s2):A(s1)
...{
cout<<s2<<endl;
}
~C()...{cout<<"C destruction!"<<endl;}
};
class D:public B,public C
...{
public:
D(char *s1,char *s2,char *s3,char *s4):B(s1,s2),C(s1,s3),A(s1)
...{
cout<<s4<<endl;
}
~D()...{cout<<"D destruction!"<<endl;}
};
int main()
...{
D d("A construction!","B construction!","C construction!","D construction!");
return 0;
}
* 虚继承构造函数的调用顺序
************************************************************************/
#include<iostream.h>
#include <stdio.h>
class A
...{
public:
A(char *s)
...{
cout<<s<<endl;
}
~A()...{cout<<"A destruction!"<<endl;}
};
class B:virtual public A
...{
public:
B(char *s1,char *s2):A(s1)
...{
cout<<s2<<endl;
}
~B()...{cout<<"B destruction!"<<endl;}
};
class C:virtual public A
...{
public:
C(char *s1,char *s2):A(s1)
...{
cout<<s2<<endl;
}
~C()...{cout<<"C destruction!"<<endl;}
};
class D:public B,public C
...{
public:
D(char *s1,char *s2,char *s3,char *s4):B(s1,s2),C(s1,s3),A(s1)
...{
cout<<s4<<endl;
}
~D()...{cout<<"D destruction!"<<endl;}
};
int main()
...{
D d("A construction!","B construction!","C construction!","D construction!");
return 0;
}
相关阅读 更多 +