&符在构造函数中使用const [英] Ampersand & with const in constructor

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

问题描述

有人可以告诉我为什么我们通常放const和&的原因吗?带有一些例如在构造函数中传递的对象.

Can some body tell me the reason why we usually put const and & with some object which is passed in the constructor for example.

Book::Book(const Date &date);

我在这里的困惑通常是&在some函数中使用了符号,因为该值是通过引用传递的,并且该函数中对该变量所做的任何更改都应在之后反映出来.但是另一方面,const表示无法对该变量进行赋值.

The confusion that i have here is that usually & sign is used in the some function because the value is passed by reference and whatever changes happen to that variable in the function should reflect afterwards. But on the other hand const says that no assignment can be done to that variable.

如果某人对此有个好主意,请告诉我原因.

If some body have some good idea about that please let me know the reason for that.

推荐答案

这样做是为了避免不必要的复制.以下面的代码为例:

This is done to avoid an unnecessary copy. Take, for example, the following code:

Book::Book(Date date):
date_(date)
{
}

调用此构造函数时,它将两次复制 date ,一次调用该构造函数,一次将其复制到成员变量中.

When you call this constructor it will copy date twice, once when you call the constructor, and once when you copy it into your member variable.

如果您这样做:

Book::Book(const Date &date):
date_(date)
{
}

日期仅复制一次.本质上,这只是一种优化.

date is only copied once. It is essentially just an optimisation.

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

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