对 ==、<、> 三个运算符分别进行重载,可见以下代码:
#include<iostream>
using namespace std;class location {
public:location(int x1, int y1) :x(x1), y(y1){};bool operator==(const location& l1) const{return x == l1.x && y == l1.y;}bool operator<(const location& l1) const {int a = x * x + y * y;int b = l1.x * l1.x + l1.y * l1.y;return a < b;}bool operator>(const location& l1) const {if (*this == l1) {return false;}if (*this < l1) {return false;}return true;}private:int x;int y;
};
int main() {location c(2, 3);location d(3, 4);if (c == d) {cout << "相等" << endl;}else if (c < d) {cout << "小于" << endl;}else {cout << "大于" << endl;}return 0;
}
函数调用运算符重载实现的函数叫做 “仿函数”,这里的话,功能是不变的,但是可以添加一些状态,就可以很灵活的加一些其他的操作,代码见下:
#include<iostream>
using namespace std;class test {public:test() {act = 0;}int operator()(int x, int y) {act++;return x + y + act;}
private:int act;
};
int main() {test testadd;cout << testadd(4, 5) << endl;//仿函数cout << testadd(4, 5) << endl;cout << testadd(4, 5) << endl;cout << testadd(4, 5) << endl;return 0;
}