我有 C# 和 Java 背景,我似乎无法理解 C++ 中指针转换的含义。
例如:
int x = 1;
char c = *((char*)&x);
它有什么作用?它有什么用?
在您的两个示例中,您都犯了错误,导致代码无法编译。所以我假设您正在尝试执行以下操作:
int x = 1;
char c = *((char*)&x);
根据您的架构,c
现在将具有最小或最高有效字节的值x
。在此示例中,该值为 0 或 1(这实际上可用于检测字节顺序)。
你的第二个例子不起作用,因为你试图忽略const
导致非法操作/错误的转换(这也称为“常量正确性”)。
编辑:关于您对“这意味着什么?”的评论:
在表达式中:&somevariable
将返回地址somevariable
.
*somevariable
将假设内容somevariable
是实际值的地址,然后返回。
在声明中:datatype
是一个普通的变量/对象。这是“按值”传递的。datatype&
是一个参考。这与 Java/C# 中的普通变量完全相同,并且通过引用传递。datatype*
是一个指针。这仅包含实际值所在的地址(见上文),并且本质上也是通过引用传递的。
实际的转换工作方式与 Java/C# 非常相似,但指针就是这样:它们指向实际值的位置。虽然这可能会让您感到困惑,但 C/C++ 中的指针的工作方式与 Java/C# 中使用的标准变量/引用非常相似。
看这个:
MyClass x; // object of MyClass
MyClass *x; // pointer to an object of MyClass - the actual value is undefined and trying to access it will most likely result in an access violation (due to reading somewhere random).
MyClass *x = 0; // same as above, but now the default value is defined and you're able to detect whether it's been set (accessing it would essentially be a "null reference exception"; but it's actually a null pointer).
MyClass &x = MyClass(); // creating a new reference pointing to an existing object. This would be Java's "MyClass x = new MyClass();"
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)