谁是名人堂球员(多重继承)

275 阅读2分钟

​持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第4天,点击查看活动详情

题目描述

1、建立如下的类继承结构:

1)一个球员类Player作为基类,具有name、height、weight等数据成员,display()等成员函数

2)从Player类派生出最有价值球员类MVP,添加属性:获奖年year

3)从Player类派生出最佳防守球员类DPOY,添加属性:获奖年year

4)从MVP和DPOY派生出名人堂类HallOfFame

2、分别定义以上类的构造函数、输出函数display及其他函数(如需要)。

3、在主函数中定义各种类的对象,并测试之,通过对象调用display函数产生输出。

输入

第一行输入球员的名字,身高,体重

第二行输入MVP获奖年

第三行输入DPOY获奖年

输出

构造四个类对象,并按照如下格式进行输出。

输入样例1

Michael 198 96
2010
2011

输出样例1

Player:
name:Michael
height:198
weight:96

MVP:
name:Michael
height:198
weight:96
reward:win the MVP reward in 2010

DPOY:
name:Michael
height:198
weight:96
reward:win the DPOY reward in 2011

Hall of fame:
name:Michael
height:198
weight:96
reward1:win the MVP reward in 2010
reward2:win the DPOY reward in 2011

思路分析

这道题涉及到类的多重继承,Player作为基类派生出MVP和DPOY,然后由这两个子类共同派生出HallOfFame类。

问题是MVP和DPOY都分别继承了Player的属性,而HallOfFame同时把它们相同的属性都继承了,这就导致了HallOfFame在访问Player的属性时会不知道是去找MVP的还是去找DPOY的。

因此,需要在父类继承的时候加上virtual修饰,这样多重继承的时候就只会继承一个相同的属性。

还有一个问题就是在多重继承的类的构造函数带参数的时候,需要把所有父辈的构造函数的参数带上,包括祖辈的。

AC代码

#include<iostream>
#include<string>
using namespace std;
class Player
{
	protected:
		string name;
		int height,weight;
	public:
		Player(string name,int height,int weight):name(name),height(height),weight(weight){}
		void display(){cout<<"Player:"<<endl<<"name:"<<name<<endl<<"height:"<<height<<endl<<"weight:"<<weight<<endl<<endl;}
};
class MVP:virtual public Player
{
	protected:
		string year;
	public:
		MVP(string year,string name,int height,int weight):year(year),Player(name,height,weight){}
		void display(){cout<<"MVP:"<<endl<<"name:"<<name<<endl<<"height:"<<height<<endl<<"weight:"<<weight<<endl<<"reward:win the MVP reward in "<<year<<endl<<endl;}
};
class DPOY:virtual public Player
{
	protected:
		string year;
	public:
		DPOY(string year,string name,int height,int weight):year(year),Player(name,height,weight){}
		void display(){cout<<"DPOY:"<<endl<<"name:"<<name<<endl<<"height:"<<height<<endl<<"weight:"<<weight<<endl<<"reward:win the DPOY reward in "<<year<<endl<<endl;}
};
class HallOfFame:public MVP,public DPOY
{
	public:
		HallOfFame(string year1,string year2,string name,int height,int weight):Player(name,height,weight),MVP(year1,name,height,weight),DPOY(year2,name,height,weight){}
		void display(){cout<<"Hall of fame:"<<endl<<"name:"<<name<<endl<<"height:"<<height<<endl<<"weight:"<<weight<<endl<<"reward1:win the MVP reward in "<<MVP::year<<endl<<"reward2:win the DPOY reward in "<<DPOY::year<<endl<<endl;}
};
int main()
{
	string year1,year2,name;
	int height,weight;
	cin>>name>>height>>weight>>year1>>year2;
	Player player(name,height,weight);
	player.display();
	MVP mvp(year1,name,height,weight);
	mvp.display();
	DPOY dpoy(year2,name,height,weight);
	dpoy.display();
	HallOfFame halloffame(year1,year2,name,height,weight);
	halloffame.display();
}