天天看點

C++引用做函數的傳回值

引用做函數的傳回值

作用:引用是可以作為函數的傳回值存在的。

注意:不要傳回局部變量引用。

用法:函數調用作為左值。

代碼示例:

#include <iostream>

using namespace std;

//引用函數的傳回值

//1.不要傳回局部變量的引用

int& test01()

{

       int a = 10;//局部變量存放在四區中的棧區

       return a;

}

//2.函數的調用可以作為左值

int& test02()

{

       static int a = 10;//靜态變量存放在全局區,全局區上的資料在程式結束後由系統釋放

       return a;

       

}

int main()

{

       //int &ref = test01();

       //cout << "ref=" << ref << endl;//第一次正确,是因為編譯器做了保留

       //cout << "ref=" << ref << endl;//第二次錯誤,是因為a的記憶體已經釋放

       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;

}      

繼續閱讀