什么是“int& foo()“是什么意思在C ++? [英] What does "int& foo()" mean in C++?

查看:536
本文介绍了什么是“int& foo()“是什么意思在C ++?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在阅读关于左值和右值的这一解释时,这些代码行突然出现在我身上:

While reading this explanation on lvalues and rvalues, these lines of code stuck out to me:

int& foo();
foo() = 42; // OK, foo() is an lvalue



我试过在g ++,但编译器说未定义引用foo()。如果我添加

I tried it in g++, but the compiler says "undefined reference to foo()". If I add

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.

此代码是什么意思?

推荐答案

解释是假设有一个值为一个函数调用,是 foo 的一些合理的实现,它返回一个有效的 int 的引用值。

The explanation is assuming that there is some reasonable implementation for foo which returns an lvalue reference to a valid int.

这样的实现可能是:

int a = 2; //global variable, lives until program termination

int& foo() {
    return a;
} 

现在,由于 foo 返回一个左值引用,我们可以为返回值赋值,如下:

Now, since foo returns an lvalue reference, we can assign something to the return value, like so:

foo() = 42;

这将更新全局 a value 42 ,我们可以通过直接访问变量或再次调用 foo 来检查:

This will update the global a with the value 42, which we can check by accessing the variable directly or calling foo again:

int main() {
    foo() = 42;
    std::cout << a;     //prints 42
    std::cout << foo(); //also prints 42
}

这篇关于什么是“int&amp; foo()“是什么意思在C ++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆