Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/131.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 这片C++;代码工作?_C++_Reference_Return Value - Fatal编程技术网

C++ 这片C++;代码工作?

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=

我在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=10;
返回x;
}
int main()
{
fun()=30;

cout
fun
返回一个引用(
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();
不能搜索和阅读引用,也不能学习
静态
局部变量的特殊之处。搜索和阅读引用,也不能学习
静态
局部变量的特殊之处。