C++的虚拟继承

C++的虚拟继承

virtual   public(或者 public virtual )语句声明了该基类为虚拟基类,
即在多重继承时所有派生类共享一个基类!这样避免了每个派生类都执行基类的构造函数,产生多个基类的副本!这样做的好处可以避免产生二义性等。

下面的例子是百度来的!!

#include <iostream>
using namespace std;
class A {
	protected:
		int a;
	public: 	
		A()
		{ 	
			a = 5;
			cout<<a<<endl;
		}
};
class B : virtual public A 
{
	public:
		B()
		{	
			a += 10;
			cout<<a<<endl;
		}
};
class C : public virtual  A  //public virtual 和virtual public 效果相同
{
	public:
		C()
		{
			a += 20;
			cout<<a<<endl;
		}
};
class D :public B, public C
{
	public:
		D()
		{
			a += 30;
			cout<<a<<endl;
		}
};
int main()
{	
	D d;
	return 0;
}

 

它的输出结果是:

A=5
B=15
C=35
D=65

如果在B类和C类继承A类时,去掉virtual,那么编译器就会报错:(我是用g++编译的)

her.cpp: In constructor ‘D::D()’:
her.cpp:36: error: reference to ‘a’ is ambiguous
her.cpp:5: error: candidates are: int A::a
her.cpp:5: error: int A::a
...

 

 


你可能感兴趣的:(C++,c,C#,百度)