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
原文链接: https://www.cnblogs.com/wanghao-boke/p/11319747.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/300536
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!