多继承下的“模棱两可”的问题
对于多继承,如果继承的多个类有相同的方法,在调用时会出现错误,例如如下的代码:
#include <iostream>
using namespace std;
class Lottery
{
public:
virtual int draw();
};
int Lottery::draw()
{
cout << "Lottery draw" << endl;
}
class GraphicalObject
{
public:
virtual int draw();
};
int GraphicalObject::draw()
{
cout << "Lottery draw" << endl;
}
class LotterySimulation : public Lottery, public GraphicalObject
{
};
int main()
{
LotterySimulation *pls = new LotterySimulation;
pls->draw();
pls->Lottery::draw();
pls->GraphicalObject::draw();
return 0;
}
错误:
E:\ProgramExcise\Code\Test\main.cpp 35 error: request for member `draw' is ambiguous
错误的意思即:draw 具有二义性
通过增加一对新的classes,就可以绕个弯解决这个问题:
#include <iostream>
using namespace std;
class Lottery
{
public:
virtual int draw();
};
int Lottery::draw()
{
cout << "Lottery draw" << endl;
}
class GraphicalObject
{
public:
virtual int draw();
};
int GraphicalObject::draw()
{
cout << "Lottery draw" << endl;
}
class AuxLottery : public Lottery
{
public:
virtual int lotteryDraw() = 0;
virtual int draw() { return lotteryDraw();}
};
class AuxGraphicalObject : public GraphicalObject
{
public:
virtual int graphicalObjectDraw() = 0;
virtual int draw(){ return graphicalObjectDraw();}
};
class LotterySimulation : public AuxLottery, public AuxGraphicalObject
{
public:
virtual int lotteryDraw();
virtual int graphicalObjectDraw();
};
int LotterySimulation::lotteryDraw()
{
cout << "lottery" << endl;
}
int LotterySimulation::graphicalObjectDraw()
{
cout << "graphicObjectDraw" << endl;
}
int main()
{
LotterySimulation *pls = new LotterySimulation();
Lottery *pl = pls;
GraphicalObject *pgo = pls;
pl->draw();
pgo->draw();
return 0;
}
但是上述这种机制,虽然能够解决掉二义性的问题,但是它无疑增加了很大的随机性。
其次一个二义性产生源于菱形继承的情况,这种情况可以通过虚继承来解决。如下这种继承情况:
A
/ \
B C
\ /
D
------Andy @ 2013-06-22