如果存在具有不同参数的继承成员,为什么对 C++ 结构函数的调用不明确?

Why is a call to a C++ struct's function ambiguous if there are inherited members with different parameters?

本文关键字:C++ 为什么 结构 函数 不明确 调用 成员 存在 继承 参数 如果      更新时间:2023-10-16

代码在下面。我有一个单个函数f((,并且在我的类D中有一个函数f(int(,所以如果两个函数都有不同的参数,为什么call call cligun?

struct A {
    void f() {}
};
struct B: virtual A {
    void f(int i) {}
};
struct C: virtual A {
    void f() {}
};
struct D: B, C {
};
int main()
{
    D d;
    d.f(5); //ambiguous
}

此处的问题是成员名称查找,该查找是在评估哪些函数可行并应用过载分辨率之前发生的。当名称查找从两个或多个无关的基类中找到名称时,这被认为是模棱两可的查找,这立即无效。

有关更多详细信息,请在类成员定义中阅读有关不合格的名称查找的信息。(这实际上不是您在这里拥有的上下文,但是相同的规则适用于成员访问表达式。(

您可以使用合格的ID来指定要查找的基础类别来解决此问题:

d.B::f(5);

或者,您可以直接在D中明确可见两个功能:

struct D: B, C {
    using B::f;
    using C::f;
};

呼叫是模棱两可的,因为即使隐藏了a的 f(),struct d的碱基a和c均具有称为 void f()的函数。为了消除歧义,您应该在d。

中声明f((
struct A {
    void f() {}
};
struct B: virtual A {
    void f(int i) {}   // <  hides A::f(), even if signature is different,
};
struct C: virtual A {
    void f() {}        // <  hides A::f()
};
struct D: B, C {
                       // f(...) functions in both base... which one hides the other?
};