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

标签 c++ pointers casting lvalue rvalue

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

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/

相关文章:

python - 映射是否可以转换

c++ - 如果 header 位于预编译 header xcode 中,则找不到默认模板参数

c++ - C++ 中的非对称虚拟继承菱形

c - 为什么从两个不同的进程访问时共享内存值会发生变化?

C 指针数组

r - 分配给 LHS 上的空索引(空方括号 x[]<-)

c++ - 'itoa' : function does not take 1 arguments & 'c' : undeclared identifier

c# - 为什么即使 GetLastError 为 0,CLRHosting API 也无法正常工作?

c++ - 我的 C 风格字符串表现得很奇怪

java - 将对象转换到列表会导致未检查的转换警告