Вопрос

If I inherit a function with the same name but different signatures from different base classes, an attempt to call the function generates an error claiming the call is ambiguous. The same functions in a single base class do not generate the error. Why is this?

First case, 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)

Second case, no errors, 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;
}
Это было полезно?

Решение

Overloading occurs between names defined in the same scope. When multiple bases define the same name, the definitions are in different scopes, so they don't overload. If you add two using declarations to Derived you can pull the two names into Derived and they will then overload.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top