C ++如何选择重载函数来调用? [英] How does C++ pick which overloaded function to call?
问题描述
class X {};
class Y {};
class Both:public X,public Y {};
我的意思是说我有两个类,然后是第三个类,它扩展了两个(多重继承)。
$ b
现在说我有一个在另一个类中定义的函数:
void doIt(X * arg){}
void doIt(Y * arg){}
doIt(new Both());
这会导致编译时错误,说明函数调用是不明确的。
除了这个,C ++编译器决定调用是否模糊并引发错误(如果有的话),情况如何?编译器如何确定这些情况是什么?简单来说:如果它不明确,那么编译器会给你一个错误,迫使你选择。在你的代码片段中,你会得到一个不同的错误,因为 new Both()
的类型是一个指向两者的指针
,而重载的 doIt()
通过值来接受它们的参数(即它们不接受指针)。如果将> doIt()
更改为 X *
和 Y *
,编译器会给你一个关于模糊函数调用的错误。
如果你想明确地调用其中一个或另一个,适当地:
void doIt(X * arg){}
void doIt(Y * arg){}
Both * both = new Both;
doIt((X *)both); //调用doIt(X *)
doIt((Y *)both); //调用doIt(Y *)
同时删除;
Say I have three classes:
class X{};
class Y{};
class Both : public X, public Y {};
I mean to say I have two classes, and then a third class which extends both (multiple-inheritance).
Now say I have a function defined in another class:
void doIt(X *arg) { }
void doIt(Y *arg) { }
and I call this function with an instance of both:
doIt(new Both());
This causes a compile-time error, stating that the function call is ambiguous.
What are the cases, besides this one, where the C++ compiler decides the call is ambiguous and throws an error, if any? How does the compiler determine what these cases are?
Simple: if it's ambiguous, then the compiler gives you an error, forcing you to choose. In your snippet, you'll get a different error, because the type of new Both()
is a pointer to Both
, whereas both overloads of doIt()
accept their parameters by value (i.e. they do not accept pointers). If you changed doIt()
to take arguments of types X*
and Y*
respectively, the compiler would give you an error about the ambiguous function call.
If you want to explicitly call one or the other, you cast the arguments appropriately:
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;
这篇关于C ++如何选择重载函数来调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!