在c ++中复制构造函数 [英] Copy Constructor in c++

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

问题描述

大家好,



我对Copy construtor有疑问。我的问题是:



我们都知道复制构造函数的原型是



MyClass(const MyClass&);



我的问题是,我们需要通过CONST。据我所知,因为没有错误的身体应该改变对象,我试图从中复制。还有其他原因让它成为CONST。



我被问到我们可以为复制构造函数提供自己的实现。所以在我的重载副本construtor。我会确保我传递的对象没有改变。然后我们为什么需要CONST。





提前致谢

Hi All,

I have a query regarding Copy construtor. And my question is:

As we all know the prototype of copy constructor is

MyClass (const MyClass &);

my question is, WHy do we need to pass CONST. As per my knowledge, Because no body by mistake should change the object, i am trying to copy from. Is there any other reason for making it CONST.

I was asked that we can give our own implementation for copy constructor. So in my overloaded copy construtor. I will make sure that my passed object is not getting changed. Then why do we need CONST.


Thanks in advance

推荐答案

这是一个约束。 编译器保证您的实现不会触及传递的对象。不要误会我的意思,我们知道你是一个好人,无论如何我们更信任编译器。
That's a constraint. The compiler guarantees your implementation won't touch the passed object. Don't get me wrong, we know you are a good fellow, anyway we trust more the compiler.


你的知识是正确的:使用const for * any * function参数阻止*(意外) )在函数的实现中更改它们。它是对调用该函数的人的一个承诺,即作为参数传递的对象不会被更改。



此外,它允许您将表达式传递给函数而不是变量:在这种情况下,编译器将创建一个保存表达式结果的临时对象。如果参数未声明为const,则编译器将引发错误,因为将引用传递给非const的临时值是错误的!



*:当然,实现仍然可以抛弃const - 它不应该,但它是可能的。
Your knowledge is correct: using const for *any* function parameter prevents* (accidentally) changing them inside the implementation of the function. It is a promise to the person calling that function, that the object being passed as parameter will not be changed.

Additionally it enables you to pass an expression to the function, rather than a variable: in that case, the compiler will create a temporary object that holds the result of the expression. If the parameter is not declared as const, then the compiler will raise an error, because passing a reference to a temporary that is not const is an error!

*: Of course, the implementation can still cast away const - it shouldn't, but it's possible.


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

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