简体   繁体   English

C ++赋值运算符可以是自由函数吗?

[英]Can C++ assignment operators be free functions?

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? 操作员可以/不能被定义为自由功能是否有限制?如果是,为什么?

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). 赋值运算符应由具有一个参数的非静态成员函数实现(C ++ 03 13.5.3 / 1)。

operator() , operator[] , and operator-> must also be implemented as non-static member functions. operator()operator[]operator->也必须实现为非静态成员函数。

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). 特定于类的operator newoperator delete (及其变体)必须实现为静态成员函数(请注意,这些函数是隐式静态的,即使它们未使用static关键字声明)。

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:). 因此,他们不想将双胞胎分开(避免双胞胎悖论:)。

PS What's a shame in C++, is that you cannot add a member to existing class. PS C ++中的一个耻辱是,您无法将成员添加到现有类中。 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. 如果可能,您可以通过不在类定义标头中声明私有函数来解耦标头和cpp依赖关系。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM