运算符重载
为什么重载的operator=强制成为成员函数($13.5.3),而不是复合赋值运算符,例如operator+=($13.5.2)?我在这里忽略了什么吗?
Why is overloaded operator= mandated to be a member function ($13.5.3), but not a compound assignment operator e.g. operator+= ($13.5.2)? Am I overlooking something here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果用户未定义复制分配
operator=
作为成员,则始终由编译器提供。我认为只是为了简单起见并避免意外的歧义,要求operator=
不能定义为自由函数。当您想要从用户定义类型分配到内置类型时,转换运算符会处理这种情况。
A copy assignment
operator=
, as a member, is always provided by the compiler if the user doesn't define one. I believe that it was only for simplicity and to avoid unexpected ambiguities that it was made a requirement thatoperator=
can't be defined as a free function.Conversion operators take care of the case when you want to assign from a user-defined type to a built-in type.
您引用的部分有关于隐藏
operator=
基类实现的内容这也可能是您问题的答案,因为编译器需要知道它是否应该生成an
operator=
它必须知道是否定义了这样的运算符,如果可以在类之外定义它,则编译器无法知道它是否在不同的翻译单元中定义。例如
,另一方面,复合运算符不是隐式定义的,因此没有理由强制将它们声明为成员函数。
The sections you reference have this to say about hiding base class implementations of
operator=
This may also be the answer to your question, since the compiler needs to know if it should generate an
operator=
it must know if such an operator was defined, if it could be defined outside the class the compiler couldn't know if it was defined in a different translation unit.e.g.
Compound operators, on the other hand, are not implicitly defined therefore there is no reason to force them to be declared as member functions.
除了默认构造函数和复制构造函数之外,operator= 在 C++ 中也受到特殊对待。这意味着,即使您没有声明,编译器也会为您提供默认实现。但默认实现并不总是适合您的类需求的行为,这就是为什么您应该显式声明它们(或通过分配私有可见性来隐藏它们)。
为什么默认构造函数、复制构造函数和赋值运算符如此特殊?因为它们涉及标准变量初始化和参数传递:当您按值(而不是通过引用或指针)将类类型参数传递给函数时,将调用这些操作以将其内容复制到堆栈。
Along with default and copy constructors, operator= is also treated specially in C++. That means, even if you don't declare one, the compiler will provide a default implementation for you. But default implementations are not always the behaviour that suits your class' needs, that's why you should declare them explicitly (or hide them, by assigning private visibility).
And why is default constructor, copy constructor and assignment operator so special? Because they are involved in standard variable initialization and parameter passing: when you pass a class-typed parameter to a function by value (not by reference or pointer), these operations are called to copy it's content to the stack.
正如 Charles 所说,如果用户未定义复制赋值
operator=
,则编译器始终会提供复制赋值。此编译器提供的成员函数始终优先于非成员函数,因此即使您可以将其定义为非成员函数,也不会调用它。As stated by Charles, a copy assignment
operator=
is always provided by the compiler if the user doesn't define one. This compiler provided member function would always have precedence over a non-member function, so even if you could define it as a non-member function, it wouldn't be called.