【问题标题】:Why is this piece of code "not ambigious!" - virtual functions为什么这段代码“没有歧义!” - 虚拟功能
【发布时间】:2015-12-06 06:35:20
【问题描述】:

为什么下面的代码没有歧义以及它是如何正常工作的?

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

【问题讨论】:

  • 这不是virtual inheritance的例子,这是完全不同的东西。
  • @BoPersson 与virtual inheritance 有何不同?
  • 嗯,是的@BoPersson,但我使用的继承是钻石问题的一个例子。我对“歧义调用”有点困惑

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


【解决方案1】:

这不是模棱两可的,因为Child 定义了它自己对drawShape 的覆盖,ch.drawShape 将调用该函数。如果Child 没有提供对drawShape 的覆盖,则调用将不明确。

【讨论】:

  • 但即使我删除了基类中的 virtual 关键字,它仍然可以正常工作!
  • @highlander141 这里的基类与歧义无关。正如我已经解释的那样,正是在通话时所知道的事情使它模棱两可。
  • @highlander141 默认情况下继承虚拟行为。您说即使删除关键字 virtual 后您也看不到问题。关键字 virtual 在派生类中是可选的。如果未指定,任何在基类中定义为 virtual 的函数在派生类中默认为 virtual。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-10-06
  • 1970-01-01
  • 1970-01-01
  • 2019-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多