1. 程式人生 > >C++中引用的用法和實驗程式碼

C++中引用的用法和實驗程式碼

主要有以下兩點:

1.當函式返回值為引用型別時,沒有複製return的物件,而返回的是return的物件本身。

2.返回引用時,要求在函式的引數中,包含有以引用方式或指標方式存在的,需要被返回的引數。

實驗程式碼如下:

#include <iostream>
using namespace std;
int a = 5;
int c = 2;
int &b = c;
int& add(int& x);
int& add(int& x)
{
    x=x+1;
    cout<<"a="<<a<<endl;
    cout<<"&x="<<&x<<endl;
    return x;
}
int main()
{
    cout<<&a<<endl;
    cout<<&b<<endl;
    cout<<&c<<endl;
    cout<<add(a)<<endl;
    cout<<&add(a)<<endl;
    b = add(a);
    cout<<a<<endl;
    cout<<b<<endl;
    cout<<c<<endl;
    cout<<&a<<endl;
    cout<<&b<<endl;
    cout<<&c<<endl;
    return 0;
}

執行結果:

0x602070
0x602074
0x602074
a=6
&x=0x602070
6
a=7
&x=0x602070
0x602070
a=8
&x=0x602070
8
8
8
0x602070
0x602074
0x602074