为什么这段代码是"not ambigious!"——虚函数
Why is this piece of code "not ambigious!" - virtual functions
为什么下面的代码没有歧义,它是如何工作的?
#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
的覆盖,那么调用将是不明确的。
为什么下面的代码没有歧义,它是如何工作的?
#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
的覆盖,那么调用将是不明确的。