C++如何选择要调用的重载函数?

Cla*_*diu 4 c++ inheritance programming-languages function multiple-inheritance

说我有三个班:

class X{};
class Y{};
class Both : public X, public Y {};
Run Code Online (Sandbox Code Playgroud)

我的意思是说我有两个类,然后是第三个类,它们都扩展了(多重继承).

现在说我在另一个类中定义了一个函数:

void doIt(X *arg) { }
void doIt(Y *arg) { }
Run Code Online (Sandbox Code Playgroud)

我用这两个实例调用这个函数:

doIt(new Both());
Run Code Online (Sandbox Code Playgroud)

这会导致编译时错误,表明函数调用不明确.

有什么情况,除了这个,C++编译器决定调用是不明确的并且抛出错误,如果有的话?编译器如何确定这些情况是什么?

Ada*_*eld 7

简单:如果它不明确,那么编译器会给你一个错误,迫使你选择.在你的代码片段中,你会得到一个不同的错误,因为类型new Both()是指针Both,而两个重载都是doIt()按值接受它们的参数(即它们不接受指针).如果你改变doIt()采取的各类参数X*Y*分别,编译器会为您提供有关暧昧函数调用错误.

如果要显式调用其中一个,则适当地转换参数:

void doIt(X *arg) { }
void doIt(Y *arg) { }
Both *both = new Both;
doIt((X*)both);  // calls doIt(X*)
doIt((Y*)both);  // calls doIt(Y*)
delete both;
Run Code Online (Sandbox Code Playgroud)


Jer*_*ten 5

我用gcc得到这个错误:

jeremy@jeremy-desktop:~/Desktop$ g++ -o test test.cpp
test.cpp: In function ‘int main(int, char**)’:
test.cpp:18: error: call of overloaded ‘doIt(Both&)’ is ambiguous
test.cpp:7: note: candidates are: void doIt(X)
test.cpp:11: note:                 void doIt(Y)
Run Code Online (Sandbox Code Playgroud)