Can C++ assignment operators be free functions?

大城市里の小女人 提交于 2019-11-28 09:46:15

The assignment operator must be a non-static member function and must have exactly one parameter:

An assignment operator shall be implemented by a non-static member function with exactly one parameter (C++03 13.5.3/1).

operator(), operator[], and operator-> must also be implemented as non-static member functions.

Class-specific operator new and operator delete (and variants thereof) must be implemented as static member functions (note that these are implicitly static, even if they are not declared with the static keyword).

It cannot.

The reason, I guess, has to do with copy constructor. They have very similar semantics, and, you cannot define a copy constructor outside of a class just like other constructor. So, they didn't want to separate the twins far apart (to avoid the twins paradox:).

P.S. What's a shame in C++, is that you cannot add a member to existing class. There's no low-level reason for that. If it would be possible, you could decouple header and cpp dependencies by not declaring private functions in the class definition header.

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