在C++中,c-casting与类型或参考类型有什么区别?c-casting类型与c-casting类型的参考
foo = (unsigned int) whatever;
// Is this the same as:
foo = (unsigned int&) whatever;
在C++中,c-casting与类型或参考类型有什么区别?c-casting类型与c-casting类型的参考
foo = (unsigned int) whatever;
// Is this the same as:
foo = (unsigned int&) whatever;
不,它甚至不是相同的。
(在某些情况下,投的确切性质取决于什么whatever
是。我假设的whatever
类型无关unsigned int
。)
C-铸造引用类型unsigned int &
相当于执行reinterpret_cast
于该类型
foo = reinterpret_cast<unsigned int &>(whatever);
其是由定义相当于
foo = *reinterpret_cast<unsigned int *>(&whatever);
whatever
在这种情况下必须是左值。
换句话说,铸造参考只是类型双关的另一种方法。你很简单重新解释whatever
占用的内存作为一个unsigned int
对象。一般情况下,行为是不确定的。例如,如果sizeof whatever
小于unsigned int
的大小,重新解释还将涉及一些甚至不属于whatever
的“狂野”内存。
同时,非参考C-cast只是一个值转换,而不是内存重新解释。对于算术转换为unsigned int
,它相当于static_cast
(但如果whatever
是指针,则相当于reinterpret_cast
)。它读取的值的whatever
并根据语言转换规则(如果存在转换)将其转换为unsigned int
类型。
例如,这
float f = 5;
unsigned int i = (unsigned int) f;
将值的f
转换成键入unsigned int
,这意味着i
将接收值5
。同时,如果你的平台上尺寸unsigned int
和float
具有相同的大小,那么这个
unsigned int i = (unsigned int &) f;
会与实际价值5
作为unsigned int
类型的对象重新诠释float
对象f
的内部对象表示。 i
的结果值通常是不可预知的。通常它不会接近5
(在流行的实现中,您将仅收到i
中原始float
值的IEE754表示)。
如果在源类型和目标类型之间存在继承关系,则Nitpick,转换为引用也可以是静态转换。在一些具有多重继承的场景中,这实际上很重要,因为'reinterpret_cast'将提供一个指向源对象开始的指针,但'static_cast'会纠正指针以引用目标对象的开始。 (无论如何,因为问题是关于'unsigned int') –
@DavidRodríguez - dribeas:是的,谢谢。为了避免将答案与细节重载,我假定我们正在专门讨论将其转换为'unsigned int'。 – AnT
reinterpret_cat iz在你的天花板,看着你转换你的vrblz –
这些是不同的问题,我确信这两个问题之前已经被问及过很多次。尽管如此,避免“重复”票选的好办法。你愿意为每个问题提出一个问题吗? –
2不是静态铸造。这是C型铸造。改用'static_cast'。 –
没有任何保证(在C++中)所有枚举都适合于一个无符号整数。在你的例子中,它会。 –