Overloading operator= as Non-Member [duplicate]
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-memberoperator=
hides the memberoperator=
- 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.
精彩评论