您的位置:首页 > 其它

继承中的二义性归属问题

2015-08-13 15:28 411 查看
当一个基类产生多个子类,这些子类又产生新的子类时,调用基类的成员函数会产生二义性问题

代码示例

/*          human
/            \
mother            father
\             /
son
*/
#include <iostream>
using namespace std;
class human
{
public:
void stand(){ cout << "hehe" << endl; }
};
class mother :public human
{

};
class father :public human
{

};
class son :public father, public mother
{

};
int main()
{
son tom;
//tom.stand()//会有二义性,编译器不知道stand()函数是指从mother继承来的还是从father继承来的
tom.mother::stand();//指明stand()函数是从mother那里继承来的,用::标识符(成员限定符)
return 0;
}


结果演示



定义为虚基类可解决二义性问题,不必再添加成员限定符

代码演示

#include <iostream>
using namespace std;
class human
{
public:
void stand(){ cout << "人类能够直立行走" << endl; }
};
class mother :virtual public human   //virtual的意思是虚的,也就是定义虚基类
{

};
class father :virtual public human  //每个子类都定义虚基类
{

};
class son :public father, public mother
{
public:

};
int main()
{
father mike;
mike.stand();
mother jane;
jane.stand();
human man;
man.stand();
son tom;
tom.stand();
return 0;
}


结果演示



或者是每个类都定义自己的成员函数,函数名可以相同,编译时自动调用

代码示例

#include <iostream>
using namespace std;
class human
{
public:
void stand(){cout<<"人类能够直立行走"<<endl;}
};
class mother:virtual public human
{
public:
void stand(){cout<<"母类能够直立行走"<<endl;}
};
class father:virtual public human
{
public:
void stand(){cout<<"父类能够直立行走"<<endl;}
};
class son:public father,public mother
{
public:
void stand(){cout<<"子类能够直立行走"<<endl;}
};
int main()
{
son tom;
tom.stand();
father mike;
mike.stand();
mother jane;
jane.stand();
human man;
man.stand();
return 0;
}


结果演示

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: