#include <iostream>
using namespace std;
void f(int &a)
{
cout << "f(" << a << ") is being called" << endl;
}
void g(const int &a)
{
cout << "g(" << a << ") is being called" << endl;
}
int main()
{
int a = 3, b = 4;
f(a + b); //编译错误,把临时变量作为非const的引用参数传递了
g(a + b); //OK,把临时变量作为const&传递是允许的
}
const_ref.cpp: In function `int main()':
const_ref.cpp:14: error: invalid initialization of non-const reference of type '
int&' from a temporary of type 'int'
const_ref.cpp:4: error: in passing argument 1 of `void f(int&)' 而在g(a+b)中,由于g定义的参数是const int&,编译通过。 问题是为什么临时变量作为引用参数传递时,必须是常量引用呢?很多人对此的解释是临时变量是常量,不允许赋值,改动,所以当作为非常量引用传递时,编译器就会报错。这个解释在关于理解临时变量不能作为非const引用参数这个问题上是可以的,但不够准确。事实上,临时变量是可以被作为左值(LValue)并被赋值的,请看下面的代码:
#include <iostream>
using namespace std;
class CComplex {
friend CComplex operator+(const CComplex &cp1, const CComplex &cp2);
friend ostream& operator<<(ostream &os, const CComplex &cp);
private:
int x;
public:
CComplex(){}
CComplex(int x1) {
x = x1;
}
};
CComplex operator+(const CComplex &cp1, const CComplex &cp2)
{
CComplex cp3;
cp3.x = cp1.x + cp2.x;
return cp3;
} ostream& operator<<(ostream &os, const CComplex &cp)
{
os << cp.x;
return os;
}
int main()
{
CComplex a(2), b(3), c(4);
cout << (a + b) << endl;
cout << ((a + b) = c) << endl; //临时对象作为左值
return 0;
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有