如果我从不同的基类继承具有相同名称但签名不同的函数,则尝试调用该函数会生成一个错误,声称该调用不明确。单个基类中的相同函数不会产生错误。为什么是这样?
第一种情况, 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;
}