为什么多重继承具有不同签名的方法是不明确的

Why is multiply inheriting a method with different signatures ambiguous?

本文关键字:方法 不明确 多重继承 为什么      更新时间:2023-10-16

如果我从不同基类继承了一个具有相同名称但不同签名的函数,则尝试调用该函数会生成一个错误,声称调用不明确。单个基类中的相同函数不会生成错误。为什么会这样?

第一种情况,http://ideone.com/calH4Q

#include <iostream>
using namespace std;
struct Base1
{
    void Foo(double param)
    {
        cout << "Base1::Foo(double)" << endl;
    }
};
struct Base2
{
    void Foo(int param)
    {
        cout << "Base2::Foo(int)" << endl;
    }
};
struct Derived : public Base1, public Base2
{
};
int main(int argc, char **argv)
{
    Derived d;
    d.Foo(1.2);
    return 1;
}
prog.cpp: In function ‘int main(int, char**)’:
prog.cpp:27:7: error: request for member ‘Foo’ is ambiguous
prog.cpp:14:10: error: candidates are: void Base2::Foo(int)
prog.cpp:6:10: error:                 void Base1::Foo(double)

第二种情况,没有错误,http://ideone.com/mQ3J7A

#include <iostream>
using namespace std;
struct Base
{
    void Foo(double param)
    {
        cout << "Base::Foo(double)" << endl;
    }
    void Foo(int param)
    {
        cout << "Base::Foo(int)" << endl;
    }
};
struct Derived : public Base
{
};
int main(int argc, char **argv)
{
    Derived d;
    d.Foo(1.2);
    return 1;
}

重载发生在相同作用域中定义的名称之间。当多个基定义相同的名称时,这些定义在不同的范围内,因此它们不会重载。如果向Derived添加两个using声明,则可以将这两个名称拉入Derived,然后它们将重载。