[C++之旅] 4 C++的引用

[C++之旅] 4 C++的引用

基本数据的引用

    int apples = 4;
    int &apples_a = apples; //apples_a is quote of apples
    cout << "apples = " << apples << endl;
    apples_a = 15;          //modify the quote
    cout << "apples = " << apples << endl;

apple_a为apples的引用,修改apple_a等同于修改apples

结构体的引用

    typedef struct
    {
        int x;
        int y;
    }Coor;

    Coor c1;                //declare a struct variable
    Coor &c2 = c1;          //declare a quote of struct variable,the mean is modify c2 is equivalent to modify c1
    c1.x = 15;
    c2.y = 10;              //assign a value to the struct variable
    cout << "x = " << c1.x << ",y = " << c1.y << endl;

c2为c1结构体的引用,修改结构体c2等同于修改结构体c1

指针的引用

    int apples_b = 10;
    int *apples_p = &apples_b;      //apples_p is a pointer to apples_b
    int *&apples_q = apples_p;      //apples_q is the reference of pointer apples_p
    *apples_p = 12;
    cout << "apples_b = "
        << apples_b
        << endl;
    *apples_q = 15;
    cout << "apples_b = "
        << apples_b
        << endl;

指针apple_p指向变量apple_b,修改 *apple_p等同于修改apple_b的值;指针apples_q为apple_p的引用,修改 *apple_q等同于修改 *apples_p的值,即apple_b = *apple_p = *apple_q;

引用做函数参数

函数:

void swap(int &a, int &b)
{
    int c = 0;
    c = a;
    a = b;
    b = c;
    cout << "swap two variable" << endl;
}

调用方式:

swap(a1,b1);

此处与C语言不一样,c语言使用指针进行交换数据,调用时需加上取地址符,而在C++中使用引用的方法则不需要。上函数中a为a1的引用即a1等同于a,b同理,因此更换a、b的值即是更换a1与b1的值。

完整程序

#include 

using namespace std;

typedef struct
{
    int x;
    int y;
}Coor;

//use quote swap two variable
void swap(int &a, int &b)
{
    int c = 0;
    c = a;
    a = b;
    b = c;
    cout << "swap two variable" << endl;
}

int main(void)
{
    //reference to basic data types
    int apples = 4;
    int &apples_a = apples; //apples_a is quote of apples
    cout << "apples = " << apples << endl;
    apples_a = 15;          //modify the quote
    cout << "apples = " << apples << endl;
    //reference of structure type
    Coor c1;                //declare a struct variable
    Coor &c2 = c1;          //declare a quote of struct variable,the mean is modify c2 is equivalent to modify c1
    c1.x = 15;
    c2.y = 10;              //assign a value to the struct variable
    cout << "x = " << c1.x << ",y = " << c1.y << endl;
    //reference of pointer type
    int apples_b = 10;
    int *apples_p = &apples_b;      //apples_p is a pointer to apples_b
    int *&apples_q = apples_p;      //apples_q is the reference of pointer apples_p
    *apples_p = 12;
    cout << "apples_b = "
        << apples_b
        << endl;
    *apples_q = 15;
    cout << "apples_b = "
        << apples_b
        << endl;

    int a, b;
    a = 4566;
    b = 123;
    cout << " a = "
        << a
        << " b = "
        << b
        << endl;
    swap(a, b);
    cout << " a = "
        << a
        << " b = "
        << b
        << endl;

    system("pause");
    return 0;
}

你可能感兴趣的:([C++之旅] 4 C++的引用)