如何调用'call by value '和'call by reference'重载函数?
How to call 'call by value ' and 'call by reference' overloaded function?
我有两个重载函数,一个 "call by value" 和另一个 "call by reference"。
int f (int a)
{
//code
}
int f (int &a)
{
//code
}
但是如果我传递 const int
,它会调用 "pass by value" 函数,为什么?
const int a=3;
f(a);//calls the call by value function.Why?
因为a
是一个const int
,所以这告诉编译器你不想修改a
。 a
不能通过引用传递(只能通过const&
),因为如果是引用,f
可以修改它,但是f
不允许,因为a
是 const
.
所以唯一合法的重载是传值一 - int f(int a)
.
const int
类型的左值不能转换为 int
类型的左值(因为那样会丢弃限定条件)。所以 int&
重载不可行,默认情况下 int
重载获胜。函数的参数全部进行左值右值转换,结果绑定到函数参数上。
我有两个重载函数,一个 "call by value" 和另一个 "call by reference"。
int f (int a)
{
//code
}
int f (int &a)
{
//code
}
但是如果我传递 const int
,它会调用 "pass by value" 函数,为什么?
const int a=3;
f(a);//calls the call by value function.Why?
因为a
是一个const int
,所以这告诉编译器你不想修改a
。 a
不能通过引用传递(只能通过const&
),因为如果是引用,f
可以修改它,但是f
不允许,因为a
是 const
.
所以唯一合法的重载是传值一 - int f(int a)
.
const int
类型的左值不能转换为 int
类型的左值(因为那样会丢弃限定条件)。所以 int&
重载不可行,默认情况下 int
重载获胜。函数的参数全部进行左值右值转换,结果绑定到函数参数上。