为什么左值转换有效? [英] Why does an lvalue cast work?
问题描述
我今天第一次看到这种演员阵容,我很好奇为什么会这样.我认为以这种方式铸造会分配给临时成员,而不是班级成员.使用 VC2010.
I saw this kind of cast for the first time today, and I'm curious as to why this works. I thought casting in this manner would assign to the temporary, and not the class member. Using VC2010.
class A
{
public:
A() :
m_value(1.f)
{
((float)m_value) = 10.f;
}
const float m_value;
};
推荐答案
它不应该工作.使用强制转换表示法到 float
的显式类型转换将是纯右值(第 5.4 节):
It shouldn't work. An explicit type conversion to float
with cast notation will be a prvalue (§5.4):
表达式 (T)
cast-expression 的结果是 T
类型.如果 T 是左值引用类型或函数类型的右值引用,则结果是左值;如果 T 是对象类型的右值引用,则结果是 xvalue;否则结果是纯右值.
The result of the expression
(T)
cast-expression is of typeT
. The result is an lvalue if T is an lvalue reference type or an rvalue reference to function type and an xvalue if T is an rvalue reference to object type; otherwise the result is a prvalue.
我强调了.
赋值运算符需要一个左值作为其左操作数(第 5.17 节):
The assignment operator requires an lvalue as its left operand (§5.17):
都需要一个可修改的左值作为它们的左操作数,并返回一个引用左操作数的左值.
All require a modifiable lvalue as their left operand and return an lvalue referring to the left operand.
纯右值不是左值.
这篇关于为什么左值转换有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!