5. 一元运算符的重载
C++ 能够重载的一元运算符有:正号(+)、负号(+)、取反(~)、取地址(&)、解引用(*)、指针成员访问(->)、逻辑非(!)、自增(++)、自减(--)运算符。
以成员函数方式重载一元运算符时,成员函数通常不需要给定参数,因为他们操作数都是 this。
示例
以下以重载负号(-)运算符为例,可以使用 - 运算将负数的将 Complex 类型的对象的实部和虚部都取符号的负向操作。
// filename: op_minus.cpp
#include <iostream>
using namespace std;
class Complex {
public:
Complex(double r=0, double i=0): real(r), image(i){}
Complex operator -() {
return Complex(-real, -image);
}
private:
double real;
double image;
// 友元全局函数声明
friend ostream & operator << (ostream & o, const Complex & c);
};
ostream & operator << (ostream & o, const Complex & c) {
o << "(" << c.real << "+" << c.image << "i)";
return o;
}
int main(int argc, char * argv[]) {
Complex c1(1, 2);
cout << "+c1:" << c1 << endl;
cout << "-c1:" << -c1 << endl;
return 0;
}
编译和运行结果如下
weimz@mzstudio:~$ g++ -o op_minus op_minus.cpp
weimz@mzstudio:~$ ./op_minus
+c1:(1+2i)
-c1:(-1+-2i)
可见 -c1 将 c1 实部和虚部的符号都进行了反向变化。