重载逻辑运算符被认为是不好的做法? [英] Overloading logical operators considered bad practice?

查看:79
本文介绍了重载逻辑运算符被认为是不好的做法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

超载&& ;, ||是一个坏主意吗?或逗号运算符,为什么?

Is it a bad idea to overload &&, || or comma operator and Why?

推荐答案

我不会重载operator&&operator||.即使您定义了一个生成布尔代数的类(例如,有限集),重载operator&operator|可能也是一个更好的选择.

I wouldn't overload operator&& or operator||. Even if you define a class that gives rise to a Boolean algebra (finite sets, for example), it would probably be a better choice to overload operator& and operator|.

原因是C ++程序员希望operator&&operator||具有特殊的语义:它们是短路的,即,如果不需要,请勿评估其右手参数.您无法通过重载获得此行为,因为您将定义一个函数.

The reason is that C++ programmers expect special semantics for operator&& and operator||: they are short-circuited, i.e. don't evaluate their right-hand argument if not necessary. You can't get this behavior by overloading, since you'll be defining a function.

重载operator,已在例如 Boost.Assign 库.这也是我知道的唯一一个超载示例,而且我自己从未考虑过超载.您最好有一个非常具体的用例,而不适合其他运算符.

Overloading operator, has been done in e.g. the Boost.Assign library. This is also the only example of its overloading that I know, and I've never even considered overloading it myself. You'd better have a very specific use case for it where no other operator is suited.

这篇关于重载逻辑运算符被认为是不好的做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆