C++ 关系运算符重载
C++ 允许重载任何一个关系运算符,重载后的关系运算符可用于比较类的对象
C++ 语言支持各种关系运算符 ( < 、 > 、 <= 、 >= 、 == 等),它们可用于比较 C++ 内置的数据类型
下面,我们就来写一个范例重载小于关系运算符 ( < )
/** * file: main.cpp * author: 简单教程(www.twle.cn) * * Copyright © 2015-2065 www.twle.cn. All rights reserved. */ #include <iostream> class Rect { private: double width; double height; public: Rect(double a, double b ) { width = a; height = b; } double area() { return width * height; } // 重载小于运算符 ( < ), 按照面积比大小, bool operator <(Rect& that) { return this->area() < that.area(); } }; int main() { Rect r1(3.0, 5.0), r2( 1.5, 4.5); if ( r1 < r2 ) std::cout << "r1 is less than r2\n"; else std::cout << "r1 is large than r2\n"; return 0; }
编译运行以上代码,输出结果如下:
r1 is large than r2