C++开发初级


916 浏览 5 years, 3 months

10.3 重载比较运算符

版权声明: 转载请注明出处 http://www.codingsoho.com/

重载比较运算符

比较运算符(例如>、<以及==)是另一组对类有用的运算符。与基本的算术运算符类似,它们也应该是全局友元函数,这样就可以在运算符的左边以及右边使用隐式转换。所有比较运算符返回值都是bool。当然,您可以改变返回类型,但是并不建议这么做。下面是比较运算符的声明以及定义:

class SpreadsheetCell
{
 public:
  friend bool operator==(const SpreadsheetCell& lhs,
             const SpreadsheetCell& rhs);
  friend bool operator<(const SpreadsheetCell& lhs,
            const SpreadsheetCell& rhs);
  friend bool operator>(const SpreadsheetCell& lhs,
            const SpreadsheetCell& rhs);
  friend bool operator!=(const SpreadsheetCell& lhs,
             const SpreadsheetCell& rhs);
  friend bool operator<=(const SpreadsheetCell& lhs,
             const SpreadsheetCell& rhs);
  friend bool operator>=(const SpreadsheetCell& lhs,
             const SpreadsheetCell& rhs);
};

代码取自 OperatorOverloading\SpreadsheetCell.h

bool operator==(const SpreadsheetCell& lhs, const SpreadsheetCell& rhs)
{
  return (lhs.mValue == rhs.mValue);
}

bool operator<(const SpreadsheetCell& lhs, const SpreadsheetCell& rhs)
{
  return (lhs.mValue < rhs.mValue);
}

bool operator>(const SpreadsheetCell& lhs, const SpreadsheetCell& rhs)
{
  return (lhs.mValue > rhs.mValue);
}

bool operator!=(const SpreadsheetCell& lhs, const SpreadsheetCell& rhs)
{
  return (lhs.mValue != rhs.mValue);
} 

bool operator<=(const SpreadsheetCell& lhs, const SpreadsheetCell& rhs)
{
  return (lhs.mValue <= rhs.mValue);
}

bool operator>=(const SpreadsheetCell& lhs, const SpreadsheetCell& rhs)
{
  return (lhs.mValue >= rhs.mValue);
}

代码取自 OperatorOverloading\SpreadsheetCell.cpp

前面重载的运算符针对mValue,而这是一个双精度植。大多数时候,对于浮点数执行相等或者不相等的测试并不是个好主意.您应该使用精确测试(epsilon test)。

当类中的数据成员比较多的时候,比较每个数据成员可能比较痛苦。然而,当实现了==以及<之后,可以根据这两个运算符编写其他比较运算符。例如,下面的operator>=定义使用了operator< 。

bool operator>=(const SpreadsheetCell& lhs, const SpreadsheetCell& rhs)
{
  return !(lhs.mValue < rhs.mValue);
}

您可以使用这些运算符将某个SpreadsheetCell与其他SpreadsheetCell进行比较,也可以与double以及int比较:

if(myCell > aThirdCell || myCell < 10){
    cout << myCell.getValue(); << endl;
}

代码取自 OperatorOverloading\SpreadsheetCellTest.cpp