引用

2017-11-04  本文已影响0人  BlinKer

0x00 引用的语法

引用的声明方法:类型标识符 &引用名=目标变量名;

int a;
int& ra = a;
int num = 2;
    int* pointer = #
    int& quote = num;
    int num2 = num;

    cout << &num << endl << pointer << endl << &quote << endl << &num2 << endl;

输出结果如下:

image.png

0x01 将引用作为函数参数

将引用作为函数参数类似指针传参,可以改变参数的实际值:

int re(int& t, int& arc)
{
    int temp;
    temp = t;
    t = arc;
    arc = temp;

    return 0;
}

    int add1 = 100;
    int add2 = 200;

    re(add1, add2);
    cout << add1 << endl << add2 << endl;

输出结果如下:

image.png

0x02 返回值为引用类型的函数

int test2 = 1;

int& re(int& t, int arc)
{
    t = arc + 1;

    return t;
}

    re(test2, 1) = 3;
    cout << re(test2, 1) << endl<< test2 <<endl;

输出结果如下:

image.png
上一篇 下一篇

猜你喜欢

热点阅读