运算符重载格式
返回值类型 operator 运算符名称 (形参表列){//TODO:}
operator是关键字,专门用于定义重载运算符的函数。我们可以将operator 运算符名称这一部分看做函数名,对于上面的代码,函数名就是operator+。
重载“-” 示例:
#include<iostream>using namespace std;class Distance {private:int feet;float inches;public:Distance(int f, float i) :feet(f), inches(i){};void show() {cout << feet << " feet " << inches << " inches" << endl;}Distance operator -() {feet = -feet;inches = -inches;return Distance(feet, inches);}};int main() {Distance d1(5, 11);d1.show();-d1;d1.show();}
