C++引用(引用做返回值的注意事项)

    科技2024-05-23  77

    ```cpp 在这里插入代码片 ```#include"stdafx.h" #include <iostream> using namespace std; //此处返回局部变量引用 int &test01() { int a=10;//局部变量的地址存放在栈区,栈区开辟的数据由编译器自动释放 return a; } int &test02() { static int a=10;//静态变量存放在全局区 return a; } /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int main() { //不能返回局部变量 int&rel=test01(); cout<<rel<<endl;//编译第一次时数据是对的,因为栈区数据只能暂时储存 cout<<rel<<endl; cout<<rel<<endl; // int&rel=test02(); cout<<rel<<endl;//全局区数据在程序结束后由操作系统释放 cout<<rel<<endl; cout<<rel<<endl; system("pause"); return 0; }

    在这里插入代码片

    Processed: 0.011, SQL: 8