在 c++ 中重载 +=
如果我已经重载了operator+和operator=,我还需要重载吗 运算符+=这样的东西可以工作:
MyClass mc1, mc2;
mc1 += mc2;
If I've overloaded operator+ and operator= do I still need to overload
operator+= for something like this to work:
MyClass mc1, mc2;
mc1 += mc2;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
是的,您也需要定义它。
然而,一个常见的技巧是定义
operator+=
,然后根据它实现operator+
,如下所示:如果您以相反的方式执行此操作(使用 + 来实现 +=),您会在 += 运算符中进行不必要的复制操作,这可能是性能敏感代码中的问题。
Yes, you need to define that as well.
A common trick however, is to define
operator+=
, and then implementoperator+
in terms of it, something like this:If you do it the other way around (use + to implement +=), you get an unnecessary copy operation in the += operator which may be a problem i performance-sensitive code.
Operator+= 不是 + 和 = 的组合,因此您确实需要显式重载它,因为编译器不知道为您构建谜题。 但您仍然可以通过在operator+=内部使用已经定义/重载的运算符来受益。
operator+= is not a composite of + and =, therefore you do need to overload it explicitly, since compiler do not know to build puzzles for you. but still you do able to benefit from already defined/overloaded operators, by using them inside operator+=.
是的你是。
Yes, you do.
如果这里真正的问题是,“我不想编写大量重复的运算符,请告诉我如何避免它”,那么答案可能是:
http://www.boost.org/doc/libs/1_38_0/libs/utility/operators.htm
不过,语法看起来有点繁琐。 由于我自己从未使用过它,因此我无法向您保证它确实很简单。
If the real question here is, "I don't want to write a load of repetitive operators, please tell me how to avoid it", then the answer may be:
http://www.boost.org/doc/libs/1_38_0/libs/utility/operators.htm
The syntax looks a little fiddly, though. As I've never used it myself, I can't reassure you that it's simple really.