为什么这段代码“没有暧昧!” - 虚拟功能

时间:2015-12-06 06:35:21

标签: c++ multiple-inheritance virtual-functions ambiguous name-lookup

为什么下面的代码没有含糊不清以及它是如何工作的?

#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();
}

1 个答案:

答案 0 :(得分:3)

它不含糊,因为Child定义了它自己的drawShape覆盖,而ch.drawShape将调用该函数。如果Child没有提供drawShape的覆盖,则调用将是不明确的。