c++ - 为什么具有相同名称但不同签名的多重继承函数不被视为重载函数?

标签 c++ scope overloading multiple-inheritance

以下代码片段在编译过程中产生了“对 foo 的模糊调用”错误,我想知道是否有任何方法可以在不完全限定对 foo 的调用的情况下解决此问题:

#include <iostream>

struct Base1{
    void foo(int){
    }
};

struct Base2{
    void foo(float){
    }
};

struct Derived : public Base1, public Base2{
};

int main(){
    Derived d;
    d.foo(5);

    std::cin.get();
    return 0;
}

所以,问题如题。想法?我的意思是,以下操作完美无缺:

#include <iostream>

struct Base{
    void foo(int){
    }
};

struct Derived : public Base{
    void foo(float){
    }
};

int main(){
    Derived d;
    d.foo(5);

    std::cin.get();
    return 0;
}

最佳答案

成员查找规则在第 10.2/2 节中定义

The following steps define the result of name lookup in a class scope, C. First, every declaration for the name in the class and in each of its base class sub-objects is considered. A member name f in one sub-object B hides a member name f in a sub-object A if A is a base class sub-object of B. Any declarations that are so hidden are eliminated from consideration. Each of these declarations that was introduced by a using-declaration is considered to be from each sub-object of C that is of the type containing the declara-tion designated by the using-declaration. If the resulting set of declarations are not all from sub-objects of the same type, or the set has a nonstatic member and includes members from distinct sub-objects, there is an ambiguity and the program is ill-formed. Otherwise that set is the result of the lookup.

class A {
public:
  int f(int);

};
class B {
public:
   int f();

};
class C : public A, public B {};
int main()
{
     C c;
     c.f(); // ambiguous
}

因此您可以使用using 声明A::fB::f 来解决这种歧义

class C : public A, public B {
     using A::f;
     using B::f;

};

int main()
{
     C c;
     c.f(); // fine
}

第二个代码可以完美运行,因为 void foo(float) 在 C 的范围内。实际上 d.foo(5); 调用 void foo(float) 而不是 int 版本。

关于c++ - 为什么具有相同名称但不同签名的多重继承函数不被视为重载函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29835682/

相关文章:

c++ - 使控制台输出 "verbose"或不输出的最快方法

javascript - typescript :需要在从异步函数读取的全局范围内声明一个常量

c# - 除了可选参数之外,两个方法具有相同的签名

可以抛出和不能抛出的方法中的 Swift 类型推断

c++ - 以 C++ 方式格式化文本

c++ - 继承私有(private)构造函数

c++ - 显示一年中每一天的新信息

Windows批处理括号范围

java - 将 json 解析值与用户输入的值进行匹配

c++ - 有什么建议可以精确地制作以下 c++ 代码吗?