关于c ++函数重载的一个混淆 [英] A confusion about c++ function overloading
问题描述
<$我在c ++中尝试了默认参数值和函数重载, c $ c>第19行:错误:重载的'add()'调用不明确
我编译的是:
#include< iostream>
使用namespace std;
void add(int a = 1,int b = 1){
cout<< a + b;
}
void add(){
int a = 2,b = 2;
cout<< a + b;
}
int main(){
add();
返回0;
}
解释它为什么不明确? Thx提前。
因为两个签名都与调用相匹配。
加();
可以解释为 add(1,1)
或 add()
。当你写 void add(int a = 1,int b = 1)
,你告诉编译器 - 如果我打电话给 add
不带任何参数,我希望您将它们默认为 1
$ b
最重要的是,当
-
如果您希望它打印
2
,请删除不带参数的版本。 / p> -
如果您希望打印
>4
,请从第一个版本中删除默认参数。
I was trying out default argument values and function overloading in c++ by compiling the following code and I was surprised by the output which was :
Line 19: error: call of overloaded 'add()' is ambiguous
The code I compiled is :
#include <iostream>
using namespace std;
void add(int a=1, int b=1){
cout<<a+b;
}
void add(){
int a =2, b=2;
cout<<a+b;
}
int main(){
add();
return 0;
}
Any explanations why it is ambiguous? Thx in advance.
Because both signatures match the call.
add();
can be interpreted as either add(1,1)
or add()
. When you write void add(int a=1, int b=1)
, you're telling the compiler - "Listen dude, if I call add
with no parameters, I want you to default them to 1
"
Most importantly, what do YOU expect to happen when you call add()
with no parameters?
If you expect it to print
2
, remove the version that takes no parameters.If you expect it to print
4
, remove the default parameters from the first version.
这篇关于关于c ++函数重载的一个混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!