刚刚开始学习 C++,遇到了这个示例,其中函数返回对局部静态变量的引用。
int& fun() {
static int x = 10;
return x;
}
int main() {
int &z = fun();
cout << fun() << " ";
z = 30;
cout << fun();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
该线有什么int &z = fun();作用?我们是否将一个引用存储在另一个引用中?我是这门语言的新手,我所知道的是引用变量就像别名一样引用变量。谁能解释一下这是如何工作的?
我们是否将一个引用存储在另一个引用中?
不,引用甚至不需要有“存储”。引用是为了简化编程。auto& thing = foo.get_value_reference();然后使用thing使代码更容易编写和调试。thing当您查看最终的汇编代码时,它甚至不必作为单独的实体存在。
int orig;
int& a = orig;
int& b = a;
Run Code Online (Sandbox Code Playgroud)
b现在是指orig--没有别的。您无法引用参考。