引用做函數的返回值

#include<iostream>
#include<string>

using namespace std;

//引用做函數的返回值

//引用的注意事項
//1、不要返回局部變量的引用
//2、函數的調用可以作爲 左值

// static c = 100;

int& test01()
{
    int a = 10;  //局部變量存放在四區中的 棧區
    return a;
}

int& test02()  //
{
    static int a = 10;
    
    return a;
}

int main()
{
    int a = 10;
    //創建引用
    int b = 20;
    // int &ref = test01();  //非法操作
    // cout << "ref: " << ref << endl;
    int &ref2 = test02();  //非法操作
    cout << "ref: " << ref2 << endl;

    test02() = 1000;  //如果函數的返回值是引用,這個函數調用可以作爲左值
    cout << "ref2: " << ref2 << endl;

}

輸出爲:

ref: 10
ref2: 1000
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章