C++ 重载比较操作符
C++语言支持各种关系运算符,比如(<
, >
, <=
, >=
, ==
等),可以用来比较C++的内置数据类型。
你可以重载任意一个这些操作符,用于比较类的对象。
下面的示例解释了如何重载<
操作符,你也可以类似地重载其他关系运算符。
#include <iostream>
using namespace std;
class Distance {
private:
int feet; // 0 to infinite
int inches; // 0 to 12
public:
// required constructors
Distance() {
feet = 0;
inches = 0;
}
Distance(int f, int i) {
feet = f;
inches = i;
}
// method to display distance
void displayDistance() {
cout << "F: " << feet << " I:" << inches <<endl;
}
// overloaded minus (-) operator
Distance operator- () {
feet = -feet;
inches = -inches;
return Distance(feet, inches);
}
// overloaded < operator
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;
}
当上面的代码被编译并执行时,会产生以下结果−。
D2 is less than D1