gpt4 book ai didi

c++ - C++ 中的转换和指针转换

转载 作者:行者123 更新时间:2023-11-30 00:51:42 24 4
gpt4 key购买 nike

谁能解释一下为什么这是真的:

char *p;
short i;
long l;

(long *) p = &l ; /* Legal cast */
(long) i = l ; /* Illegal cast */

我知道它与左值和右值有关,但 (long *) p 不应该是右值吗?

编辑:

抱歉,我好像把自己和其他人搞糊涂了,我在阅读时问了这个"this MDSN"我很惊讶地看到这个语法,我看到它是一个特殊的功能,允许将左值转换为左值,只要它的大小相同。

最佳答案

这些表达式都不合法,它们都应该无法编译。

C++11, 5.17.1:

The assignment operator (=) and the compound assignment operators all group right-to-left. All require a modifiable lvalue as their left operand and return an lvalue referring to the left operand.

5.4:

Explicit type conversion (cast notation) [expr.cast] 1 The result of the expression (T) cast-expression is of type T. 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.

所以这两个表达式都违反了这些约束。

关于c++ - C++ 中的转换和指针转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20871139/

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