gpt4 book ai didi

c++ - 为什么可以接受对不同类型变量的常量引用?

转载 作者:太空宇宙 更新时间:2023-11-04 14:57:01 24 4
gpt4 key购买 nike

我在看 http://msdn.microsoft.com/en-us/library/szywdw8k%28VS.80%29.aspx部分代码对我来说没有意义。

int iVar;
const long& LongRef3 = iVar; // OK

为什么当 LongRef3 声明为常量时,LongRef3 可以引用 iVar,即使它们是不同的类型?

根据这个:Why does the constness of a reference affect whether it can be initialized with a variable of a different type?

“因为它创建了一个临时 int,其中 double 被转换,可变引用不能绑定(bind)到临时对象,而 const 可以。”这对我来说没有意义。正在创建什么临时 int?

我为什么要这样做?什么时候将其声明为 const int& 更有用?

我可以使用的类型有限制吗?

编辑:为什么这个问题被否决了?我相信我已经很好地解释了这个问题。

最佳答案

int iVar;
const long& LongRef3 = iVar;

引用LongRef3不引用 iVar , 但类型为 long 的临时值从 iVar 的值初始化.代码有点类似这样:

int iVar;
const long __injected_iVar__ = iVar;
const long& LongRef3 = __injected_iVar__;

你可以试着看看当你做 &iVar 时会发生什么对比&LongRef3 .

Why would I want to do this? When would it be useful over declaring it const int&?

在这种简单的情况下,它可能没有用。但是,如果函数参数通过 const 引用获取某些内容,那么您可以使用兼容类型甚至文字作为此类参数。

And is there a limit to which types I can do this with?

仅适用于兼容类型;但它也适用于用户定义的结构和类,只要它们提供它们之间的转换。

关于c++ - 为什么可以接受对不同类型变量的常量引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7987555/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com