“int& foo()”在 C++ 中是什么意思?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36477542/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What does "int& foo()" mean in C++?
提问by Sossisos
While reading this explanationon lvalues and rvalues, these lines of code stuck out to me:
在阅读关于左值和右值的解释时,这些代码行让我印象深刻:
int& foo();
foo() = 42; // OK, foo() is an lvalue
I tried it in g++, but the compiler says "undefined reference to foo()". If I add
我在 g++ 中尝试过,但编译器说“对 foo() 的未定义引用”。如果我添加
int foo()
{
return 2;
}
int main()
{
int& foo();
foo() = 42;
}
It compiles fine, but running it gives a segmentation fault. Just the line
它编译得很好,但运行它会出现分段错误。就行
int& foo();
by itself both compiles and runs without any problems.
本身编译和运行都没有任何问题。
What does this code mean? How can you assign a value to a function call, and why is it not an rvalue?
这段代码是什么意思?如何为函数调用赋值,为什么它不是右值?
回答by TartanLlama
The explanation is assuming that there is some reasonable implementation for foo
which returns an lvalue reference to a valid int
.
解释是假设有一些合理的实现foo
返回一个对有效的左值引用int
。
Such an implementation might be:
这样的实现可能是:
int a = 2; //global variable, lives until program termination
int& foo() {
return a;
}
Now, since foo
returns an lvalue reference, we can assign something to the return value, like so:
现在,由于foo
返回一个左值引用,我们可以为返回值分配一些东西,如下所示:
foo() = 42;
This will update the global a
with the value 42
, which we can check by accessing the variable directly or calling foo
again:
这将a
使用 value更新全局42
,我们可以通过直接访问变量或foo
再次调用来检查它:
int main() {
foo() = 42;
std::cout << a; //prints 42
std::cout << foo(); //also prints 42
}
回答by Kate Gregory
All the other answers declare a static inside the function. I think that might confuse you, so take a look at this:
所有其他答案都在函数内部声明了静态。我认为这可能会让你感到困惑,所以看看这个:
int& highest(int & i, int & j)
{
if (i > j)
{
return i;
}
return j;
}
int main()
{
int a{ 3};
int b{ 4 };
highest(a, b) = 11;
return 0;
}
Because highest()
returns a reference, you can assign a value to it. When this runs, b
will be changed to 11. If you changed the initialization so that a
was, say, 8, then a
would be changed to 11. This is some code that might actually serve a purpose, unlike the other examples.
因为highest()
返回一个引用,你可以给它赋值。运行时,b
将更改为 11。如果您将初始化更改为a
8,则将a
更改为 11。与其他示例不同,这些代码实际上可能用于某个目的。
回答by NathanOliver
int& foo();
Declares a function named foo that returns a reference to an int
. What that examples fails to do is give you a definition of that function that you could compile. If we use
声明一个名为 foo 的函数,该函数返回对 的引用int
。那些例子没有做的是给你一个你可以编译的函数的定义。如果我们使用
int & foo()
{
static int bar = 0;
return bar;
}
Now we have a function that returns a reference to bar
. since bar is static
it will live on after the call to the function so returning a reference to it is safe. Now if we do
现在我们有一个返回对 的引用的函数bar
。因为 barstatic
它将在调用该函数后继续存在,因此返回对它的引用是安全的。现在如果我们这样做
foo() = 42;
What happens is we assign 42 to bar
since we assign to the reference and the reference is just an alias for bar
. If we call the function again like
发生的情况是我们将 42bar
分配给了,因为我们分配给了引用,而引用只是 的别名bar
。如果我们再次调用该函数,例如
std::cout << foo();
It would print 42 since we set bar
to that above.
因为我们bar
在上面设置了它,所以它会打印 42 。
回答by M.M
int &foo();
declares a function called foo()
with return type int&
. If you call this function without providing a body then you are likely to get an undefined reference error.
int &foo();
声明一个foo()
以返回类型调用的函数int&
。如果您在不提供主体的情况下调用此函数,则可能会出现未定义的引用错误。
In your second attempt you provided a function int foo()
. This has a different return type to the function declared by int& foo();
. So you have two declarations of the same foo
that don't match, which violates the One Definition Rule causing undefined behaviour (no diagnostic required).
在您的第二次尝试中,您提供了一个函数int foo()
。这与由 声明的函数具有不同的返回类型int& foo();
。所以你有两个foo
不匹配的相同声明,这违反了一个定义规则,导致未定义的行为(不需要诊断)。
For something that works, take out the local function declaration. They can lead to silent undefined behaviour as you have seen. Instead, only use function declarations outside of any function. Your program could look like:
对于有效的东西,取出局部函数声明。正如您所见,它们会导致无声的未定义行为。相反,只在任何函数之外使用函数声明。您的程序可能如下所示:
int &foo()
{
static int i = 2;
return i;
}
int main()
{
++foo();
std::cout << foo() << '\n';
}
回答by Jarod42
int& foo();
is a function returning a reference to int
. Your provided function returns int
without reference.
int& foo();
是一个返回对 的引用的函数int
。您提供的函数在int
没有参考的情况下返回。
You may do
你可以做
int& foo()
{
static int i = 42;
return i;
}
int main()
{
int& foo();
foo() = 42;
}
回答by vy32
int & foo();
means that foo()
returns a reference to a variable.
int & foo();
意味着foo()
返回对变量的引用。
Consider this code:
考虑这个代码:
#include <iostream>
int k = 0;
int &foo()
{
return k;
}
int main(int argc,char **argv)
{
k = 4;
foo() = 5;
std::cout << "k=" << k << "\n";
return 0;
}
This code prints:
此代码打印:
$ ./a.out k=5
$ ./a.out k=5
Because foo()
returns a reference to the global variable k
.
因为foo()
返回对全局变量的引用k
。
In your revised code, you are casting the returned value to a reference, which is then invalid.
在您修改后的代码中,您将返回值转换为引用,该引用无效。
回答by Dar Brett
In that context the & means a reference - so foo returns a reference to an int, rather than an int.
在这种情况下,& 表示引用 - 因此 foo 返回对 int 的引用,而不是 int。
I'm not sure if you'd have worked with pointers yet, but it's a similar idea, you're not actually returning the value out of the function - instead you're passing the information needed to find the location in memory where that int is.
我不确定您是否已经使用过指针,但这是一个类似的想法,您实际上并没有从函数中返回值 - 相反,您正在传递在内存中查找位置所需的信息整数是。
So to summarize you're not assigning a value to a function call - you're using a function to get a reference, and then assigning the value being referenced to a new value. It's easy to think everything happens at once, but in reality the computer does everything in a precise order.
因此,总而言之,您没有为函数调用分配值 - 您正在使用函数来获取引用,然后将被引用的值分配给新值。很容易认为所有事情都是同时发生的,但实际上,计算机是按照精确的顺序完成所有事情的。
If you're wondering - the reason you're getting a segfault is because you're returning a numeric literal '2' - so it's the exact error you'd get if you were to define a const int and then try to modify its value.
如果你想知道 - 你得到段错误的原因是因为你返回了一个数字文字“2” - 所以如果你要定义一个 const int 然后尝试修改它,这就是你得到的确切错误价值。
If you haven't learned about pointers and dynamic memory yet then I'd recommend that first as there's a few concepts that I think are hard to understand unless you're learning them all at once.
如果您还没有了解指针和动态内存,那么我建议您先学习,因为我认为有一些概念很难理解,除非您一次全部学习它们。
回答by IceFire
The example code at the linked page is just a dummy function declaration. It does not compile, but if you had some function defined, it would work generally. The example meant "If you had a function with this signature, you could use it like that".
链接页面上的示例代码只是一个虚拟函数声明。它不会编译,但如果你定义了一些函数,它通常可以工作。这个例子的意思是“如果你有一个带有这个签名的函数,你可以这样使用它”。
In your example, foo
is clearly returning an lvalue based on the signature, but you return an rvalue that is converted to an lvalue. This clearly is determined to fail. You could do:
在您的示例中,foo
显然是根据签名返回左值,但您返回的是转换为左值的右值。这显然注定要失败。你可以这样做:
int& foo()
{
static int x;
return x;
}
and would succeed by changing the value of x, when saying:
并且会通过更改 x 的值来成功,当说:
foo() = 10;
回答by psj01
The function you have, foo(), is a function that returns a reference to an integer.
您拥有的函数 foo() 是一个返回对整数的引用的函数。
So let's say originally foo returned 5, and later on, in your main function, you say foo() = 10;
, then prints out foo, it will print 10 instead of 5.
因此,假设最初 foo 返回 5,然后在您的主函数中,您说foo() = 10;
,然后打印出 foo,它将打印 10 而不是 5。
I hope that makes sense :)
我希望这是有道理的 :)
I'm new to programming as well. It's interesting to see questions like this that makes you think! :)
我也是编程新手。看到这样的问题让你思考很有趣!:)