C++ 这片C++;代码工作?
我在Geek For Geek中看到了下面这个例子C++ 这片C++;代码工作?,c++,reference,return-value,C++,Reference,Return Value,我在Geek For Geek中看到了下面这个例子 #include<iostream> using namespace std; int &fun() { static int x = 10; return x; } int main() { fun() = 30; cout << fun(); return 0; } Answer is 30. #包括 使用名称空间std; int&fun() { 静态int x=
#include<iostream>
using namespace std;
int &fun()
{
static int x = 10;
return x;
}
int main()
{
fun() = 30;
cout << fun();
return 0;
}
Answer is 30.
#包括
使用名称空间std;
int&fun()
{
静态int x=10;
返回x;
}
int main()
{
fun()=30;
coutfun
返回一个引用(int&
)到static
变量x
在fun
的作用域内。因此从本质上讲,fun()=30
语句是fun::x=30
。注意这是安全的,因为x
是static
fun
返回一个引用(int&
)到static
变量x
的fun
s范围内。因此本质上语句fun()=30
是fun::x=30
。请注意,这是安全的,因为x
是静态的
函数局部静态变量第一次初始化到函数中,并一直保持到程序结束。因此,当您调用
fun() = 30;
您返回对该变量的引用,然后为其赋值30。由于该变量仍处于活动状态,它将保留该值。然后
cout << fun();
cout函数局部静态变量第一次初始化到函数中,并一直保持到程序结束
fun() = 30;
您返回对该变量的引用,然后为其赋值30。由于该变量仍处于活动状态,它将保留该值。然后
cout << fun();
不能搜索和阅读引用,也不能学习静态
局部变量的特殊之处。搜索和阅读引用,也不能学习静态
局部变量的特殊之处。