读书人

关于运算符重载的一个有关问题

发布时间: 2012-03-11 18:15:39 作者: rapoo

关于运算符重载的一个问题
#include <iostream>
using namespace std;

class Integer {
int i;
public:
Integer(int ii) : i(ii) {}
const Integer
operator+(const Integer& rv) const {
cout < < "operator+ " < < endl;
return Integer(i + rv.i);
}
Integer&
operator+=(const Integer& rv) {
cout < < "operator+= " < < endl;
i += rv.i;
return *this;
}
};

int main() {
cout < < "built-in types: " < < endl;
int i = 1, j = 2, k = 3;
k += i + j;
cout < < "user-defined types: " < < endl;
Integer ii(1), jj(2), kk(3);
kk += ii + jj;
} ///:~

为什么operator+=要返回引用类型
返回一个Integer或不返回值功能上有什么区别?

[解决办法]
首先必须要有返回值 因为+=赋值操作
没有返回值 编译不通过阿

添加引用是为了提高效率
[解决办法]
返回引用一般是为了用于级联表达式和提高效率如:
Integer ii(1), jj(2), kk(3), pp(0);
pp = (kk += (ii += jj));
对上面的表达式:如果不返回引用(用返回值)则(ii += jj)返回需要创建一个临时变量用于和kk进行相加,相加后又需要创建一个临时变量再赋给pp。如果返回引用则不需要创建临时变量。当然如果级联表达式不返回值,那怎么级联呢......呵呵

读书人网 >C++

热点推荐