当赋值A=B时,是调用A的赋值运算符还是B的赋值运算符?
如果我有两个类 A 和 B 并且我执行 A=B ,则调用哪个赋值构造函数? A班的还是B班的?
If I have two classes A and B and I do A=B which assignment constructor is called? The one from class A or the one from class B?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有复制构造函数和赋值运算符。由于
A != B
,将调用复制赋值运算符。简短答案:来自 A 类的
operator =
,因为您要分配给 A 类。长答案:
A=B
不起作用,因为A
> 和B
是类类型。您可能的意思是:
在这种情况下,将调用
class A
的operator =
。在以下情况下将调用转换构造函数:
其中 A 定义为:
请注意,这会在 B 和 A 之间引入隐式转换。如果您不希望这样做,可以将转换构造函数声明为
显式
。There's copy constructor and there's assignment operator. Since
A != B
, the copy assignment operator will be called.Short answer:
operator =
from class A, since you're assigning to class A.Long answer:
A=B
will not work, sinceA
andB
are class types.You probably mean:
In which case,
operator =
forclass A
will be called.The conversion constructor will be called for the following case:
where A is defined as:
Note that this introduces implicit casting between B and A. If you don't want that, you can declare the conversion constructor as
explicit
.因此,在左侧的对象上调用该运算符。
但请确保不要错过 if 子句。
So the operator is called on the object on the left hand side.
But make sure you do not miss the if clause.