c++ - 这是否过于聪明或不安全?

标签 c++ operator-overloading

我最近正在处理一些代码,并决定在 C++ 中处理我的运算符重载,因为我以前从未真正实现过它。因此,我使用比较函数重载了矩阵类的比较运算符,如果 LHS 小于 RHS,则返回 0,如果 LHS 大于 RHS,则返回 1,如果它们相等,则返回 2。然后我在整数上利用了逻辑不在 c++ 中的属性,将我所有的比较放在一行中:

inline bool Matrix::operator<(Matrix &RHS){
  return ! (compare(*this,RHS));
}
inline bool Matrix::operator>(Matrix &RHS){
  return ! (compare((*this),RHS)-1);
}
inline bool Matrix::operator>=(Matrix &RHS){
  return compare((*this),RHS);
}
inline bool Matrix::operator<=(Matrix &RHS){
  return compare((*this),RHS)-1;
}
inline bool Matrix::operator!=(Matrix &RHS){
  return compare((*this),RHS)-2;
}
inline bool Matrix::operator==(Matrix &RHS){
  return !(compare((*this),RHS)-2);
}

显然我应该将 RHS 作为 const 传递,我可能不会再使用这个矩阵类,而且我不想编写另一个不是引用的函数来单独获取数组索引值比较器操作。

根据建议,如果比较返回 -1 表示小于,0 表示相等,1 表示正,则代码如下。

inline bool Matrix::operator<(Matrix &RHS){
  return ! (compare(*this,RHS)+1);
}
inline bool Matrix::operator>(Matrix &RHS){
  return ! (compare((*this),RHS)-1);
}
inline bool Matrix::operator>=(Matrix &RHS){
  return compare((*this),RHS)+1;
}
inline bool Matrix::operator<=(Matrix &RHS){
  return compare((*this),RHS)-1;
}
inline bool Matrix::operator!=(Matrix &RHS){
  return compare((*this),RHS);
}
inline bool Matrix::operator==(Matrix &RHS){
  return !(compare((*this),RHS));
}

我不知道这是否真的增加了可读性。

最佳答案

是的,它太聪明了——我读了这段代码,不得不考虑为什么你要从一个名为 compare 的函数中减去两个。不要让我思考。

如果您很聪明地将代码放在一行上,那么您的优先级就会困惑。您应该使用尽可能多的行来使您的代码尽可能清晰。

Programs must be written for people to read, and only incidentally for machines to execute. (Abelson & Sussman, Structure and Interpretation of Computer Programs)

关于c++ - 这是否过于聪明或不安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2845372/

相关文章:

c++ - 我的 for 循环没有给我所有的数字

c++ - 与 PSECURITY_STRING 不兼容

c++ - 将 float float/double 的余数转换为 int

c++ - Cygwin 控制台转储大量神秘输出然后键入 1;2;6;22c

c++ - 对于列表排序,有没有办法让多个运算符重载具有相同的参数?

c++ - 使用声明和 const 重载

c++ - 为什么这个 while 在给定一个字符串时会永远循环?

c# - C# 中基于接口(interface)编程的运算符重载

c++ - 为 std::unordered_map 中的 const std::reference_wrapper 重载 operator==

c++ - 为什么 `(void *)&` 会得到变量的地址?