c++左值引用作为函数形参时的注意要点

来源:互联网 发布:区域填充算法代码 编辑:程序博客网 时间:2024/05/22 17:35
#include<iostream>
using namespace std;

void f(int i)
{
    i += 5;
}

void ref_f(int &i)
{
    i += 5;
    cout << "after change :" << i << endl;
}

void ref_swap(int &a, int &b)
{
    int temp = a;
    a = b;
    b = temp;
}


int main()
{
    int temp_i = 8;
    double temp_d = 8.5;

    cout << "before call f() temp_i is: " << temp_i << endl;
    f(temp_i);
    cout << "after call f() temp_i is: " << temp_i << endl;

    cout << "before call f() temp_d is: " << temp_d << endl;
    f(temp_d);
    cout << "after call f() temp_d is: " << temp_d << endl;

    cout << "before call ref_f() temp_i is: " << temp_i << endl;
    ref_f(temp_i);
    cout << "after call ref_f() temp_i is: " << temp_i << endl;

    
    //ref_f(temp_d); :对于非const类型的引用参数,类型必须完全匹配,
    //否则会进行类型转换,而生成一个临时变量,然后让i引用它
    //ref_f(temp_i + 4);这里其时也生成了临时变量
    long one = 4, two = 5;
    //ref_swap(one, two); 这是个很明显的例子,将创建两个临时变量的值,然后交换两个临时变量的值
    //而a与b的值不变
    //编译失败的原因在于:c++规定,如果接受引用参数的函数的意图是修改作为参数传递的参量,则创建临时
    //变量阻止这种意图的实现,而c++的做法是,在这种情况下禁止创建临时变量
    //见c++ primer plus 第六版 p263
    //实际上,这种做法的目的在于不能改变参量类型,你可以改变人家的名字,但你不能改变人家的性别;
    int one_ = 4, two_ = 5;
    ref_swap(one_, two_);  //编译成功
    //其实,这里很好理解,就说明了一个问题,引用仅仅是别名而已,实际上的类型必须一模一样
    //你大名叫王大海,小名叫二狗,但都是你,你是唯一的
    //例如
    //int &ref_one = one;  失败,反正记住几句话,用非const引用类型时,类型必须完全匹配
    const int &ref_one = one; //成功,why???????
    cout << "long one is: " << one << endl;  //输出 4
    cout << "const int &ref_one,one is: " << ref_one << endl; //输出4
    double d_one = 4.5;
    const int &ref_d_one = d_one;  //啥米?又编译成功,why??
    cout << "d_one is: " << d_one << endl;  //输出4.5
    cout << "ref_d_one is: " << ref_d_one << endl; //输出4  what?输出4,有没有搞错?
    //其实是这样的,c++规定,如果是const类型引用,则允许创建临时变量,而该引用,指向这个临时变量
    
}
0 0