C++多重继承的解决方法

二义性的产生

 简单的代码演示

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

using namespace std;

class Father
{
public:
	Father(const char* x, const char* m, int age)
	{
		cout << __FUNCTION__ << endl;
		Xing = x;
		Ming = m;
		this->age = age;
	}
	~Father() {}
	const string getDescription()const;
private:
	string Xing;    // 姓
	string Ming;	// 名
	int age;
};

class Mother
{
public:
	Mother(const char *_dance, int _age)
	{
		cout << __FUNCTION__ << endl;
		dance = _dance;
		age = _age;
	}
	~Mother(){}
	const string getDescription()const;
private:
	string dance;	// 他妈妈跳舞
	int age;		// 年龄
};

class Son : public Father, public Mother
{
public:
	Son(const char* _dance, int _age,  // mother()
		const char* x, const char* m, int age, // father()
		const char* game) //  son::game
		:Mother(_dance, _age), Father(x, m, age)   
	{
		this->game = game;
	}
	~Son(){}
	void getDescription()const;
private:
	string game;
};

const string Father::getDescription()const
{
	cout << __FUNCTION__ << endl;
	stringstream ret;
	ret << "姓:" << Xing << '\t' << "名:" << Ming
		<< '\t' << "年龄:" << age;
	return ret.str();
}

const string Mother::getDescription()const
{
	cout << __FUNCTION__ << endl;
	stringstream ret;
	ret << "dance:" << dance << '\t' << "年龄:" << age;
	return ret.str();
}

void Son::getDescription()const
{
	cout << __FUNCTION__ << endl;
	cout << Mother::getDescription() << endl;
	cout << Father::getDescription() << endl;
	return;
}


int main(void)
{
	Son wsc("迪斯科", 52, "王", "思聪", 60, "LOL");
	// 第一种解决多重继承二义性的方法
	cout << wsc.Father::getDescription() << endl;
	cout << wsc.Mother::getDescription() << endl;
	cout << "*******************************************" << endl;
	// 第二种解决多重继承二义性的方法
	wsc.getDescription();

	system("pause");
	return 0;
}

 效果演示

 希望大家点赞

猜你喜欢

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