为什么下面的代码不是模棱两可的,它如何正常工作?
#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();
}
最佳答案
它不是模棱两可的,因为Child
定义了它自己对drawShape
的覆盖,并且ch.drawShape
将调用该函数。如果Child
没有提供drawShape
的替代,则该调用将是不明确的。
关于c++ - 为什么这段代码“不模棱两可!”-虚拟函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34114791/