重载运算符=作为非成员
根据此线程的回复,operator=
不能被重载作为非成员函数。那么,举个例子,下面的代码会让编译器非常生气:
class MyClass
{
// ...
};
MyClass& operator=(MyClass& Left, MyClass& Right)
{
// ...
}
这是为什么呢?我有一个带有 getter 和 setter 的容器类,因此成员函数是不必要的,并且会破坏封装。上述线程的答案之一说,这是为了确保“L 值作为其第一个操作数被接收”,但我不完全理解这意味着什么。有人可以澄清一下吗?
此外,还有 operator=
、operator()
、operator[]
和 operator->
“oddball” 情况...?或者我应该将所有重载运算符实现为成员函数......? (我知道这样做是完全合法的,但我正在寻找更好的做法。)
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.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您的类没有赋值运算符(作为成员),编译器会默认生成一个赋值运算符,就像您不提供赋值运算符时它会生成一个复制构造函数一样。
因此,如果您稍后尝试定义非成员赋值运算符,它将“生气”。那么就会有两个!
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!
除非您声明一个,否则编译器会在您的类中声明一个
operator=
,其签名为operator= (C&, C&)
或operator= (C&, const C&)
。如果允许您重载分配,则大多数用途将是不明确的。
然后,您可能会游说附加规则来执行以下任一操作:
operator=
,则假装没有声明编译器,就像非成员operator=
隐藏成员operator=
这两种选择都会使本来就极其复杂的规则变得复杂,只为
operator=
添加一个特殊情况。很少有人愿意去那里。
而且您还没有公开此功能的合法用途。
或者,任何合理的用途。
当可以展示一些合理的用例时,C++ 规则只会变得更加复杂。
Unless you declare one, the compiler declares an
operator=
in your class with signatureoperator= (C&, C&)
oroperator= (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:
operator=
if a user declared one is visible, as if the non-memberoperator=
hides the memberoperator=
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.