使用参考参数评估函数

时间:2017-10-16 07:33:04

标签: c++ reference

#include <iostream>
using namespace std;

template <class T>
void swap1(T& a, T& b) {
    T c = a;
    a = b;
    b = c;
}

int main() {
    int n1 = 5;
    int n2 = 7;
    swap1(n1, n2);
    cout << n1 << " " << n2 << endl;

    int *p1 = &n1;
    int *p2 = &n2;
    swap1(*p1, *p2);
    cout << n1 << " "<< n2 << endl;
}

在许多语言中,当您调用函数时,首先评估其参数,然后将该函数应用于评估结果。

如果我们在此遵循此规则,swap1(n1, n2)swap1(*p1, *p2)都会评估为swap1(5, 7),这是没有意义的。

那么,在这种情况下,评估规则是什么?另外,在C ++中一般评估函数的规则是什么?

1 个答案:

答案 0 :(得分:2)

  

在许多语言中,当您调用函数时,首先评估其参数,然后将该函数应用于评估结果。

这正是C ++中发生的事情。但是,我们必须分析“评估函数的参数”实际上意味着什么。在C ++中,它意味着“使用指定为参数的表达式复制初始化参数”。复制初始化C ++引用的方法是绑定到由初始化程序设定的实体。对于左值引用(例如在<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"/> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script> <!-- Button trigger modal --> <button type="button" id="mymodal" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal"> Launch demo modal </button> <!-- Modal --> <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-body"> <div class="hfc"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <img class="mySlides w3-animate-fading" src="https://www.google.co.in/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png"/> </div> </div> </div> </div> </div>中),这意味着初始值必须是左值。 swap是左值,n1也是。由于引用需要一个左值,这就是所有的评估。

如果参数是值类型(不是引用),则将在初始化值旁边应用左值到右值转换。但由于我们正在初始化一个引用,因此不会发生这种转换。