Overloading += in c++

笑着哭i 提交于 2019-12-19 22:00:32

问题


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;

回答1:


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+=.




回答2:


Yes, you need to define that as well.

A common trick however, is to define operator+=, and then implement operator+ in terms of it, something like this:

MyClass operator+ (MyClass lhs, const MyClass& rhs){
  return lhs += rhs;
}

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.




回答3:


Yes, you do.




回答4:


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.



来源:https://stackoverflow.com/questions/1092331/overloading-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!