本文介绍重载符号操作符 -,他与减号操作符是一样的,那我们该如何区分开呢?其实符号操作符属于单目运算符,操作数只有一个。而减号操作符则是双目运算符,操作符需要两个才可以,这样我们在重载的时候,只要将控制了操作数,系统就知道我们到底是在重载哪个操作符了。
符号操作符重载问题比较多,特别是代码中返回值用 const 以及将函数修饰为 const 的必要性。在代码中我们均有注释,请大家细细品味。
#include <iostream> using namespace std; class Complex { public: Complex(float x, float y) :_x(x), _y(y) {} void display() { cout << "(x = " << _x << ", y = " << _y << ")" << endl; } // 前 const 防止出现这种语句 -c1 = Complex(4, 5); // 后 const 解决加了前 const 以后导致 -(-c1) 这种语法不通过 const Complex operator-() const { // 返回一个临时对象 return Complex(-this->_x, -this->_y); } private: float _x; float _y; }; int main(int argc, char* argv[]) { /* 基础数据类型的案例 int n = 10; cout << n << endl; cout << -n << endl; // 返回临时对象 cout << -(-n) << endl; */ Complex c1(1, 2); Complex c2 = -c1; c2.display(); c1.display(); // 普通对象调用 const 函数,保证操作数原值不被修改 Complex c3 = -(-c1); c3.display(); // 这种语法在基础数据类型中是不允许的,所以返回值必须是const // -c1 = Complex(4, 5); return 0; }