为什么下面的代码没有含糊不清以及它是如何工作的?
#include <QCoreApplication>
#include <iostream>
using namespace std;
class Shape{
public:
virtual void drawShape(){
cout << "this is base class and virtual function\n";
}
};
class Line : public Shape{
public:
virtual void drawShape(){
cout << "I am a line\n";
}
};
class Circle : public Shape{
public:
virtual void drawShape(){
cout <<" I am circle\n";
}
};
class Child : public Line, public Circle{
public:
virtual void drawShape(){
cout << "I am child :)\n";
}
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
//Shape *s;
//Line l;
Child ch;
//s = &l;
//s = &ch;
ch.drawShape(); // this is ambiguous right? but it executes properly!
//s->drawShape();
return a.exec();
}
答案 0 :(得分:3)
它不含糊,因为Child
定义了它自己的drawShape
覆盖,而ch.drawShape
将调用该函数。如果Child
没有提供drawShape
的覆盖,则调用将是不明确的。