开发者

Overloading operator= as Non-Member [duplicate]

This question already has answers here:开发者_Go百科 Why cannot a non-member function be used for overloading the assignment operator? (9 answers) Closed 8 years ago.

According to replies to this thread, operator= cannot be overloaded as a non-member function. So, for example, the following makes the compiler very angry:

class MyClass
{
    // ...
};

MyClass& operator=(MyClass& Left, MyClass& Right)
{
    // ...
}

Why is this? I have a container class with getters and setters, so a member function is unnecessary and it would break encapsulation. One of the answers to the aforementioned thread said that it's to make sure the "L-value is received as its first operand," but I don't fully understand what that means. Could someone please clarify?

Additionally, are operator=, operator(), operator[] and operator-> "oddball" cases...? Or should I implement all overloaded operators as member functions...? (I know it's perfectly legal to do otherwise, but I'm looking for the better practice.)


If your class doesn't have an assignment operator (as a member), the compiler generates one by default, just like it generates a copy constructor if you don't provide one.

Therefore it will be "angry" if you try to define a non-member assignment operator later. There will then be two!


Why is this?

Unless you declare one, the compiler declares an operator= in your class with signature operator= (C&, C&) or operator= (C&, const C&).

If you were allowed to overload assignment, most uses would be ambiguous.

Then you would likely lobby for additional rules to either:

  • pretend there is no compiler declared operator= if a user declared one is visible, as if the non-member operator= hides the member operator=
  • make your user declared assignment a better match during overloading.

Both choices would complicate rules that are already extremely complicated, adding a special case just for operator=.

Few people want to go there.

And also you haven't exposed a legitimate use for this feature.

Or, any reasonable use at all.

The C++ rules are only made even more complicated when some reasonable use-case can be showed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜