简体   繁体   English

在C ++中分配给float变量时,为什么双引用值不会改变

[英]Why double reference value doesn't change when assigned to float variable in C++

I am trying to understand the concept of assigning a float to const reference double and the value of double doesn't change if the float value updated. 我试图理解将float赋值给const引用double的概念,如果浮点值更新,则double的值不会改变。

float d = 2.0;
const double & f = d;
d = 3.0;
std::cout << d << " " << f << std::endl;

output: 输出:

 3 2

What is the reason behind this. 这背后的原因是什么?

However this issue is not seen when we set the reference variable as the same type as the other variable. 但是,当我们将引用变量设置为与另一个变量相同的类型时,不会出现此问题。

However this issue is not seen when we set the reference variable as the same type as the other variable 但是,当我们将引用变量设置为与另一个变量相同的类型时,不会出现此问题

That's the point; 这才是重点; you can't bind reference to object with different type directly. 你不能直接绑定不同类型的对象引用。

Given const double & f = d; 给定const double & f = d; , a temporary double will be constructed from d , then bound to the reference f . ,将从d构造临时double d ,然后绑定到参考f The modification on d has nothing to do with the temporary; d的修改与临时修改无关; they're two irrelevant objects. 他们是两个不相关的对象。 That's why you got different result when print out d and f . 这就是为什么你打印出df时会得到不同的结果。

BTW: Only the lvalue reference to const and rvalue reference could be bound to temporary, so const double & f = d; BTW:只有对const和rvalue引用的左值引用可以绑定到临时,所以const double & f = d; and double && f = d; double && f = d; work fine. 工作得很好。 Lvalue reference to non-const can't be bound to temporary, then double & f = d; Lvalue对非const的引用不能绑定到临时,然后double & f = d; won't work. 不行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM