【问题标题】:Overload resolution with multiple inheritance多重继承的重载解决方案
【发布时间】:2014-03-26 15:06:31
【问题描述】:

考虑以下示例 (link to ideone):

#include <iostream>

class Base1
{
public:
    void doit(){}
};

class Base2
{
    void doit(int x){}
};

class Derrived : public Base1, public Base2
{
};

using namespace std;

int main()
{
   cout << "Hello World" << endl;
   Derrived d;
   d.doit(); // doesn't work - error: request for member ‘doit’ is ambiguous
   d.::Base1::doit(); //works
   return 0;
}

Base1 和 Base2 都有带有不同输入参数的成员函数 doit,因此理论上应该自动解决重载。 但是,尝试调用 d.doit(); 失败并出现错误

prog.cpp: In function ‘int main()’:
prog.cpp:36:6: error: request for member ‘doit’ is ambiguous
    d.doit(); // doesn't work - error: request for member ‘doit’ is ambiguous
      ^
prog.cpp:18:7: note: candidates are: void Base2::doit(int)
  void doit(int x)
       ^
prog.cpp:6:10: note:                 void Base1::doit()
     void doit()
          ^

我必须输入 d.::Base1::doit();让它发挥作用。

为什么编译器在没有我明确指定的情况下无法解析要调用的函数?这是预期的行为吗??

【问题讨论】:

标签: c++ polymorphism multiple-inheritance


【解决方案1】:

是的,这是预期的行为。

在重载解析之前,会执行名称查找,它有自己的一套规则。它必须找到一个明确的名称,而您的情况没有。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-09
    • 1970-01-01
    • 2017-12-30
    • 2012-11-15
    • 2023-04-08
    • 1970-01-01
    • 2012-08-14
    相关资源
    最近更新 更多