C++语言支持各种关系运算符重载(<,>,>=,<=,==),他们可用于比较C++内置的数据类型。
支持重载任意一个关系运算符,重载后的关系运算符可以用于比较类的对象。
/*** overrealate.cpp ***/ #include<iostream> using namespace std; class Distance { private: int feet; int inches; public: Distance() { feet = 0; inches = 0; } Distance(int f,int i) { feet = f; inches = i; } void displayDistance() { cout << "F: " << feet << " I: " << inches << endl; } Distance operator- () { feet = -feet; inches = -inches; return Distance(feet,inches); } bool operator <(const Distance& d) { if(feet < d.feet) { return true; } if(feet == d.feet && inches < d.inches) { return true; } return false; } }; int main() { Distance D1(11,10), D2(5,11); if(D1 < D2) { cout << "D1 is less than D2 " << endl; } else { cout << "D2 is less than D1" << endl; } return 0; }
运行结果:
exbot@ubuntu:~/wangqinghe/C++/20190808$ ./overrelation
D2 is less than D1