首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

关于多重继承的有关问题?

2013-06-26 
关于多重继承的问题??对于下面这串代码,当同时继承两个类时,基类的函数就不能调用呢?该如何修改?#include

关于多重继承的问题??
对于下面这串代码,当同时继承两个类时,基类的函数就不能调用呢?
该如何修改?
#include<iostream>
using namespace std;

class People
{
private:
char *name;
int age;
char *sex;
public:
People()
{
name="NULL";
age=0;
sex="NULL";
}
void SetInformation(char *name,int age,char *sex)
{
this->name=name;
this->age=age;
this->sex=sex;
}
void ShowInformation()
{
cout<<"Name="<<name<<endl;
cout<<"Age="<<age<<endl;
cout<<"Sex="<<sex<<endl;
}
};

class Teacher :public People
{
private:
char *appellation; //保存职称
public:
Teacher()
{
appellation="NULL";
}
void ShowInformation()
{
People::ShowInformation();
cout<<"Appellation="<<appellation<<endl;
}
void SetAppellation(char *appellation)
{
this->appellation=appellation;
}
};

class Villagers :public People
{
private:
char *position; //保存职位
public:
Villagers()
{
position="NULL";
}
void SetPosition(char *position)
{
this->position=position;
}
};

class CountryTeacher :public Teacher/*,public Villagers*/
{
private:
int salary; //保存薪水
public:
CountryTeacher()
{
salary=0;
}
void ShowInformation()
{
Teacher::ShowInformation();
cout<<"Salary="<<salary<<endl;
}
};

int main()
{
CountryTeacher cteacher;
cteacher.SetInformation("Lamorh",21,"man");
cteacher.ShowInformation();
system("pause");
}
只继承一个,就可运行截图如下:
关于多重继承的有关问题?
当继承两个时,即把绿色部分的/* */去掉,就会出现如下错误?
关于多重继承的有关问题?
继承
[解决办法]
CountryTeacher 里面有两个 People 子对象,调用存在二义性。有两个方案。
(1) 用虚拟继承。
(2) 定义 CountryTeacher::SetInformation。
[解决办法]
一个CountryTeacher类对象中包含了两个People对象,所以你调用People::SetInformation是有二义性的。
用虚继承可以解决这个问题


class People{};
class Teacher :virtual public People{};
class Villagers :virtual public People{};
class CountryTeacher :public Teacher,public Villagers{};

热点排行