函数重载 - 传递常量与传递变量 C++
function overloading - passing constant vs passing variable C++
#include <iostream>
using namespace std;
void somefunc(int a)
{
cout<<"somefunc1";
}
void somefunc(int &b)
{
cout<<"somefunc2";
}
int main()
{
// case 1
somefunc(10); // works fine and prints somefunc1
//case2
int b=10;
somefunc(b); // generates compiler error that overloading is ambiguous
return 0;
}
在 main()
中,如果我传递一个常量(比如 10
),程序编译并运行并打印 "somefunc1"
,但是当我传递一个变量(b
时case) 编译器生成重载不明确的错误。
我不明白它在内部是如何工作的。
请帮忙!!
重载决议的规则有点复杂。这是一个简化,适用于这个特定的例子。
编译器执行的第一步是找到 "overload set",即可以使用参数调用的函数集。对于somefunc(10)
,只能调用somefunc(int)
;无法调用 somefunc(int&)
,因为 10
作为常量,不能通过(非常量)引用传递。所以重载集中只有一个函数,也就是被调用的函数。
对于somefunc(b)
,两个函数都可以调用。所以重载集有两个函数,somefunc(int)
和somefunc(int&)
。现在编译器必须确定哪个函数是参数 10
的 "best match"。并且规则是 int
和 int&
都提供了一个 "exact match",所以规则不偏爱一个,调用是有歧义的。
如果函数的第二个版本是 somefunc(const int&)
而不是 somefunc(int&)
,调用 somefunc(10)
也会有歧义。
#include <iostream>
using namespace std;
void somefunc(int a)
{
cout<<"somefunc1";
}
void somefunc(int &b)
{
cout<<"somefunc2";
}
int main()
{
// case 1
somefunc(10); // works fine and prints somefunc1
//case2
int b=10;
somefunc(b); // generates compiler error that overloading is ambiguous
return 0;
}
在 main()
中,如果我传递一个常量(比如 10
),程序编译并运行并打印 "somefunc1"
,但是当我传递一个变量(b
时case) 编译器生成重载不明确的错误。
我不明白它在内部是如何工作的。 请帮忙!!
重载决议的规则有点复杂。这是一个简化,适用于这个特定的例子。
编译器执行的第一步是找到 "overload set",即可以使用参数调用的函数集。对于somefunc(10)
,只能调用somefunc(int)
;无法调用 somefunc(int&)
,因为 10
作为常量,不能通过(非常量)引用传递。所以重载集中只有一个函数,也就是被调用的函数。
对于somefunc(b)
,两个函数都可以调用。所以重载集有两个函数,somefunc(int)
和somefunc(int&)
。现在编译器必须确定哪个函数是参数 10
的 "best match"。并且规则是 int
和 int&
都提供了一个 "exact match",所以规则不偏爱一个,调用是有歧义的。
如果函数的第二个版本是 somefunc(const int&)
而不是 somefunc(int&)
,调用 somefunc(10)
也会有歧义。