[英]What happens internally when I return a reference parameter passed to a function?
Let's say I have the following function: 假设我有以下功能:
int f(int& x)
{
x++;
return x;
}
First question, does the return statement copy the value of the reference x since the function is not returning an int&. 第一个问题,return语句是否复制了引用x的值,因为函数没有返回int&。
Second question, why can't I call the function with a literal? 第二个问题,为什么我不能用文字调用函数? What if I did want to call the function sometimes with a literal sometimes with a value? 如果我确实想要使用有时带有值的文字调用函数怎么办? I tried overloading with 我尝试过载
int f(int x)
{
x++;
return x;
}
It compiles if I call with literal. 如果我用文字调用它会编译。 But when I pass a variable I get ambiguous call error. 但是当我传递一个变量时,我得到了模糊的调用错误。 Is there a way to accomplish this? 有没有办法实现这个目标?
Maybe this is what you want: 也许这就是你想要的:
int F(const int& x) { return x + 1; }
int F(int& x) { x++; return x; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.