为类覆盖运算符==是否会自动覆盖运算符!=

或者换句话说,对于编译器来说,这两个块是否相等:

if (a!=b){
// do something
}
if (!(a==b)){
// do something
}

回答

不,我们可以轻松测试

#include <iostream>

class C {};

bool operator==(C, C) { return true; }

int main() {
  C a, b;
  std::cout << (a != b) << std::endl;
  return 0;
}

产生(在 gcc 上)

.code.tio.cpp: In function ‘int main()’:
.code.tio.cpp:9:19: error: no match for ‘operator!=’ (operand types are ‘C’ and ‘C’)
   std::cout << (a != b) << std::endl;


以上是为类覆盖运算符==是否会自动覆盖运算符!=的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>