C 大于等于运算符

新手上路,请多包涵

在 C++ 中,对于大于或等于 (“>=”) 的运算符,是否足以使运算符等于 (“=”) 和大于 (“>”) 重载以具有大于或等于 ( “>=”)?或者我是否需要重载运算符 (“>=”) 才能为其提供功能?

原文由 Vasi Marin 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.7k
2 个回答

使用一个明显的符号,“ > || == ”实际上是对 >= 的过度要求。

尽管请注意,对于 所有 关系运算符,您实际上只需要 < ,因为如果 a < bb < a 都为假,则建立等效性。事实上,这是有序 C++ 标准库容器中使用的概念之一。

原文由 Bathsheba 发布,翻译遵循 CC BY-SA 4.0 许可协议

operator >= 不是 operator >operator = 的组合。 operator >= 是它自己的运营商,但你可以用 operator < 通常你会有类似的东西

inline bool operator==(const X& lhs, const X& rhs){ /* do actual comparison */ }
inline bool operator!=(const X& lhs, const X& rhs){return !operator==(lhs,rhs);}
inline bool operator< (const X& lhs, const X& rhs){ /* do actual comparison */ }
inline bool operator> (const X& lhs, const X& rhs){return  operator< (rhs,lhs);}
inline bool operator<=(const X& lhs, const X& rhs){return !operator> (lhs,rhs);}
inline bool operator>=(const X& lhs, const X& rhs){return !operator< (lhs,rhs);}

来自 sbi 关于运算符重载的基本规则和习语是什么的 回答

原文由 NathanOliver 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题