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;
}

 效果演示

 希望大家点赞

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值