用虚继承解决多重继承造成的问题

首先我们先来看看多继承到底会造成什么问题:

 我是简化写的没有加功能,就是希望大家能更明了的理解,有问题的代码:

#include <iostream>
#include <string>
#include <Windows.h>

using namespace std;

class Tel
{
public:
	Tel() {
		this->number = "未知";
		cout << __FUNCTION__ << endl;
	}
	~Tel(){ cout << __FUNCTION__ << endl; }
protected:
	string number; // 电话号码
};

class LandLine : public Tel  // 座机
{
public:
	LandLine(){ cout << __FUNCTION__ << endl; }
	~LandLine(){ cout << __FUNCTION__ << endl; }
};

class MobilePhone : public Tel // 手机
{
public:
	MobilePhone(){ cout << __FUNCTION__ << endl; }
	~MobilePhone(){ cout << __FUNCTION__ << endl; }

};

class RadioTelephone : public LandLine, public MobilePhone
{
public:
	RadioTelephone() { cout << __FUNCTION__ << endl; }
	~RadioTelephone(){ cout << __FUNCTION__ << endl; }

	void setNumber(const char* str) {
		this->LandLine::number = str;
	}
	const string& getNumber()const {
		return this->MobilePhone::number;
	}
	
};

int main(void)
{
	RadioTelephone RT;
	RT.setNumber("13883728024");
	cout << RT.getNumber() << endl;


	system("pause");
	return 0;
}

运行效果:

大家可以在这里看看这个子对象RT的内存分布,用vs的朋友可以右键项目点击属性然后加上这个命令

 之后重新生成解决方案

 看到没 这里确实有两个number,但是像上面我写的那个代码加了::(限定符)让编译器知道操作的是那个number

就不会报错。哪怎么来解决这种问题呢?  其实只需要在上面的代码加一点点东西就可以了。请看

在继承的时候加上  virtual 虚继承。然后我们在通过上面讲的命令来看看内存分布

这时候就只有一个number了,来看运行结果

好的谢谢大家阅读。

猜你喜欢

转载自blog.csdn.net/qq_44065088/article/details/102922306