1. 程式人生 > >C++ 函式的返回值是引用

C++ 函式的返回值是引用

當函式返回值為引用時,若返回棧變數,不能成為其他引用的初始值,不能作為左值使用

若返回靜態變數或全域性變數,可以成為其他引用的初始值,即可作為右值使用,也可作為左值使用

//若返回靜態變數或全域性變數

//可以成為其他引用的初始值

//即可做右值,也可作為左值使用

#include<iostream>

using namespace std;

int getA()

{
            int a;

            a = 10;

            return a;
}

int& getA1()

{
            int a;

            a = 10;

            return a;
}

int getA4()

{
            int static b = 10;  //static的作用週期為整個程式的執行週期

            b++;

            return b;
}

int& getA3()

{
            int static b = 20;

            b++;

            return b;
}

int main()

{
            int a = getA();

            int a1 = getA1();

            int &a2 = getA1();

            cout <<"a=" <<a<< endl;                 //輸出為10

            cout << "a1=" << a1 << endl;          //輸出為10

            cout << "a2=" << a2 << endl;          //輸出為亂碼

            int b = 0;

            int b1 = 0;

            b = getA4();

            b1 = getA3();

            int &b2 = getA3();

            cout << "b=" << b << endl;                 //輸出為11

            cout << "b1=" << b1 << endl;             //輸出為21

            printf("b2=%d", b2);                              //輸出為22

            system("pause");

}
/函式返回值為引用,可以做左值

#include<iostream>

using namespace std;

//返回的僅僅是一個值

int myget1()

{
            static int a=90;

            a++;

            return a;
}

//返回的是一個變數

int& myget2()

{
            static int b=40;

            b++;

            cout <<"b="<< b<< endl;

            return b;
}

int main()

{

            int c = 20;

            int b;

            int d;

            d = myget1();

            cout << "d="<<d<< endl;

            myget2() = 20;                              //函式返回值是引用,並且可以做左值

            b = myget2();                                //函式返回值是引用,並且可以做右值

            cout << "b="<<b<< endl;

            //cout << "myget2()="<<myget2()<< endl;

            system("pause");

}