复制构造函数&赋值运算符 [英] Copy Constructor & assignment operator

查看:97
本文介绍了复制构造函数&赋值运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

亲爱的,


复制构造函数和赋值之间有什么区别

运算符。我们可以将一个对象的成员变量的值分配给

使用它们的另一个相同类型的对象。那么

的区别在哪里?

Dear All,

Whats the difference between a copy constructor and assignment
operator. We can assign the values of member variables of one object to
another object of same type using both of them. Then where is the
difference?

推荐答案

我想它们只是为了你方便以不同的方式创建

对象。例如,假设A是类,带有

构造函数A(int)和A(const A)


A a1(5);

A a2(a1);

A a3 = a2; //你总是可以使用A a3(a2)

来创建a3,但是假设你已经使用A a3(10)创建了a3,那么你想要

将a1或a2分配给a3,你必须使用赋值运算符:a3 = a1

I guess they are just for the convenience that you could create the
objects in different ways. for example, suppose A is class with
constructor A(int) and A(const A)

A a1(5);
A a2(a1);
A a3 = a2; // you can always create a3 using A a3(a2)

but suppose you have already create a3 using A a3(10), then you want to
assign a1 or a2 to a3, you have to use assignment operator: a3 = a1


am ********* @ gmail.com 写道:
亲爱的所有,

复制构造函数和赋值运算符之间的区别。我们可以使用它们两者将一个对象的成员变量的值分配给另一个相同类型的对象。那么
区别在哪里?
Dear All,

Whats the difference between a copy constructor and assignment
operator. We can assign the values of member variables of one object to
another object of same type using both of them. Then where is the
difference?




复制构造函数用于从旧的

实例初始化一个新实例,并且通过值将变量传递给函数

或函数返回值时调用。

赋值运算符用于更改现有实例以具有

与rvalue的值相同,这意味着如果实例具有内部动态内存,则实例必须被销毁并重新初始化。


如果你试图实现它们,你应该查找示例和陷阱,看看默认实现是什么(由

编译器提供)并且也理解为什么这些有时被私有。

--Paul



The copy constructor is used to initialize a new instance from an old
instance, and is called when passing variables by value into functions
or as return values out of functions.
The assignment operator is used to change an existing instance to have
the same values as the rvalue, which means that the instance has to be
destroyed and re-initialized if it has internal dynamic memory.

You should look for examples and gotchas if you''re trying to implement
them, see what the default implementation does (provided by the
compiler) and also understand why these are sometimes made private.
--Paul


感谢您的回复。我理解Copy Cons和

Assignment Operator之间的区别。但是,我无法知道何时应该使用复制

构造函数,何时应该使用赋值运算符。任何人都可以通过这个来启发我吗?

Thanks for the reply. I understood the difference between Copy Cons and
Assignment Operator. But, I could not make out when should I use copy
constructor and when should I use assignment operator. Can anyone
enlighten me on that?


这篇关于复制构造函数&赋值运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆