运算符重载:给运算符赋予新的运算规则,如可以实现对象之间的运算。
以复数运算符为例,重载 +、前置++、后置++、+= 运算符:
class CComplex {
public:
CComplex(int r = 0, int i = 0):real_(r),image_(i) { } // 构造函数
void show() {
cout << this->real_ << "+" << this->image_ << "i" << endl;
}
// 重载 + , 成员函数。 可将此重载注释,因为全局的重载也可匹配
CComplex operator+(const CComplex& src) {
return CComplex(this->real_ + src.real_
, this->image_ + src.image_);
}
// 重载 前置++, 不带参数
CComplex& operator++() {
this->real_ += 1;
this->image_ += 1;
return *this; // *this不是局部对象,出了作用域*this对象仍然存在,因此返回引用。
}
// 重载 后置++, 带参数(C++规定带int参数的就是后置++,与int数据类型无关)
CComplex operator++(int) {
CComplex cp = *this;
this->real_ += 1;
this->image_ += 1;
return cp;
// return CComplex(real_++, image_++); // 等价于上面
}
// 重载 +=
void operator+=(const CComplex& src) {
this->real_ += src.real_;
this->image_ += src.real_;
}
friend CComplex operator+(const CComplex& lhs, const CComplex& rhs);
private:
int real_; // 实部
int image_; // 虚部
};
CComplex operator+(const CComplex& lhs, const CComplex& rhs) {
return CComplex(lhs.real_ + rhs.real_, lhs.image_ + rhs.image_);
}
void test() {
CComplex cp01(10, 20);
CComplex cp02(30, 30);
/*
重载 +
*/
CComplex res01 = cp01 + cp02; // 等价于cp01.operator+(cp02);
res01.show();
// 首先找到构造函数将10转为CComplex对象,然后再相加
CComplex res02 = cp01 + 10;
res02.show();
// 调用全局 + 运算符重载
CComplex res03 = 10 + cp01;
res03.show();
/*
重载 前置++ 与 后置++
*/
CComplex cp03(1, 1);
CComplex cp04(1, 1);
CComplex res04 = ++cp03;
res04.show();
CComplex res05 = cp04++;
res05.show(); // 1+1i
cp04.show(); // 2+2i
/*
重载 +=
*/
CComplex cp05(1, 1);
CComplex cp06(2, 2);
cp05 += cp06;
cp05.show();
}