- 格式
返回值类型 operator 运算符名称 (形参表列){ //TODO: }
operator
是关键字,专门用于定义重载运算符的函数。我们可以将operator 运算符名称
这一部分看做函数名。
- 类中的重载
#include <iostream> using namespace std; class person { private: int age; public: person(int nAge) { this->age = nAge; } bool operator==(const person& ps) { if (this->age == ps.age) { return true; } return false; } }; int main() { person p1(10); person p2(10); if (p1 == p2) { cout << "p1 is equal with p2." << endl; } else { cout << "p1 is not equal with p2." << endl; } return 0; }
上述代码 bool operator==(const person& ps) 代表在类中重载了 "==" 于是可做main函数中那样的调用:p1 == p2 ,其实关键的就这里,p1 == p2等价于 p1.operator==(p2) ,p1调用,operator==是函数名,p2是传入的参数。
- 全局重载的函数
#include <iostream> using namespace std; class person { public: person(int nAge) { this->age = nAge; } int age; }; bool operator==(const person& ps, const person& ps1) { if (ps1.age == ps.age) { return true; } return false; } int main() { person p1(10); person p2(10); if (p1 == p2) { cout << "p1 is equal with p2." << endl; } else { cout << "p1 is not equal with p2." << endl; } return 0; }
全局重载函数必须要两个参数,p1 == p2又需要这样理解:当识别到符号 “==” ,于是会调用operator==函数,将p1, p2作为传参,即 operator==(p1, p2)