//返回局部变量引用
int& test01() {
int a = 10; //局部变量
return a;
}
//返回静态变量引用
int& test02() {
static int a = 20;
return a;
}
int main() {
static int a = 20;
//不能返回局部变量的引用
int& ref = test01();
cout << "ref = " << ref << endl;
cout << "ref = " << ref << endl;
//如果函数做左值,那么必须返回引用
int& ref2 = test02();
cout << "ref2 = " << ref2 << endl;
cout << "ref2 = " << ref2 << endl;
test02() = 1000;
cout << "ref2 = " << ref2 << endl;
cout << "ref2 = " << ref2 << endl;
system("pause");
return 0;
}
上述程序在运行过程中没有报错。但main函数中调用了两次test02()函数,test02()函数体中又定义了静态变量a,静态变量都存储在全局区,而全局区只在程序销毁时自动释放,意味着静态变量a只能被定义一次。而两次调用test02()的过程意味着静态变量a被定义了2次,那么为什么在main函数中静态变量a没有重复定义的报错?test02() = 1000是怎样运行的,将1000赋值给一个引用是存在解引用的过程吗?