在c++开发过程中,很容易出现的错误就是非const引用,然后涉及隐式类型转换时,很容易出现问题,有的时候不注意就会导致定位问题很难找到错误,如下代码所示:
#include <iostream>
using namespace std;
void printDouble1(double& a)
{
std::cout << "a = " << a << std::endl;
}
void printDouble2(const double& a)
{
std::cout << "a = " << a << std::endl;
}
int main()
{
int a = 10;
// error:
// printDouble1(a);
//解释: 实际上这个地方相当于代码: const double tmp = a; printDouble1(tmp);, 所以,将一个const 引用传给了非const引用
// ok
printDouble2(a);
return 0;
}
实际上,这里就是涉及到类型的隐式转换导致产生了临时变量