第三十六节 C++ 菱形问题的解决 -- 虚继承

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/dddd0216/article/details/79959337

菱形问题:三个派生类同时继承一个基类,又存在另一个派生类同时继承这三个派生类。这将导致创建三个基类对象(calss One),当我们通过Three去调用One的函数实现时, 将出现错误,编译器不知道调用哪个One的函数,这将是我们不愿意发生的。

#include <iostream>
using namespace std;

class One {
public:
	One() { cout << "One constructor" << endl; }
};

/*创建两个对象*/
class Two_1 : public One {
public:
	Two_1() { cout << "Two_1 constructor" << endl; }
};

/*创建两个对象*/
class Two_2 : public One {
public:
	Two_2() { cout << "Two_2 constructor" << endl; }
};

/*创建两个对象*/
class Two_3 : public One {
public:
	Two_3() { cout << "Two_3 constructor" << endl; }
};

/*多继承*/
class Three : public Two_1, public Two_2, public Two_3 {
public:
	Three() { cout << "Three constructor" << endl; }
};

int main()
{
	Three Object; //实例化对象,实例化了三次One类,从输出可以看出
	return 0;
}

output: 

One constructor      //实例化一次
Two_1 constructor
One constructor    //实例化两次
Two_2 constructor
One constructor      //实例化三次
Two_3 constructor

Three constructor

可以用虚继承解决上述问题。

-------------------------------------------------------------------------------------------

#include <iostream>
using namespace std;

class One {
public:
	One() { cout << "One constructor" << endl; }
};

class Two_1 : virtual public One {
public:
	Two_1() { cout << "Two_1 constructor" << endl; }
};

class Two_2 : virtual public One {
public:
	Two_2() { cout << "Two_2 constructor" << endl; }
};

class Two_3 : virtual public One {
public:
	Two_3() { cout << "Two_3 constructor" << endl; }
};

/*多继承*/
class Three : public Two_1, public Two_2, public Two_3 {
public:
	Three() { cout << "Three constructor" << endl; }
};

int main()
{
	Three Object; //实例化对象,仅实例化一个One类的对象,从输出可以看出
	return 0;
}

output:

One constructor
Two_1 constructor
Two_2 constructor
Two_3 constructor
Three constructor

阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页