c++ - 比较运算符重载

标签 c++ operators

最佳做法(在这种情况下):

bool Foo::operator==(const Foo& other) {
  return bar == other.bar;
}

// Implementation 1
bool Foo::operator!=(const Foo& other) {
  return bar != other.bar
}

// Implementation 2
bool Foo::operator!=(const Foo& other) {
  return !(*this == other);
}

对于像 >、<、<=、>= 这样的运算符,我会尽可能使用实现 2。但是,对于 != 我认为实现 1 更好,因为没有进行另一个方法调用,这是正确的吗?

最佳答案

第二个实现有一个值得注意的约束,即 == 将始终是 != 的 bool 值对立面。这可能是您想要的,它使您的代码更易于维护,因为您只需更改一个实现即可使两者保持同步。

关于c++ - 比较运算符重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10575766/

相关文章:

c++ - 正确包含基类和子类(派生类)的头文件?

c++ - 在 Qt Quick 2 中使用 QVTKOpenGLWidget

c++ - 循环读取套接字回复

java - for 循环中输出关闭

java - 为什么我的 Scanner 变量没有使用 : System. out.println(input.nextDouble()); 转换为 double 值?

c++ - 从 SQLite 获取 int 值

c++ - ListView 在 mfc 中杀死焦点

c++ - 不等于运算符需要澄清

performance - SQLITE 运算符 "="与 "< AND >"性能差异比较

c++ - 在哪里可以找到运算符重载列表?