可以 C++赋值运算符是自由函数吗?
我正在尝试这样的事情:
Foo & operator=(Foo & to, const Bar &from);
但我收到此错误:
E2239 'operator =(Foo &, const Bar &)' must be a member function
哪些运算符可以/不能定义为自由函数是否有限制,如果有,为什么?
I'm trying something like this:
Foo & operator=(Foo & to, const Bar &from);
But I'm getting this error:
E2239 'operator =(Foo &, const Bar &)' must be a member function
Are there limitations on which operators can/cannot be defined as Free Functions, and if so, why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
赋值运算符必须是非静态成员函数,并且必须只有一个参数:
operator()
、operator[]
和operator->
也必须实现为非静态成员函数。特定于类的
operator new
和operator delete
(及其变体)必须实现为静态成员函数(请注意,它们是隐式静态的,即使它们没有使用static
关键字)。The assignment operator must be a non-static member function and must have exactly one parameter:
operator()
,operator[]
, andoperator->
must also be implemented as non-static member functions.Class-specific
operator new
andoperator delete
(and variants thereof) must be implemented as static member functions (note that these are implicitly static, even if they are not declared with thestatic
keyword).它不能。
我猜原因与复制构造函数有关。它们具有非常相似的语义,并且您不能像其他构造函数一样在类外部定义复制构造函数。所以,他们不想把双胞胎分开太远(以避免双胞胎悖论:)。
PS C++ 中的一个遗憾是您无法向现有类添加成员。这没有低级的原因。如果可能的话,您可以通过不在类定义标头中声明私有函数来解耦标头和 cpp 依赖关系。
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.