gpt4 book ai didi

使用指针的 C++ 类型转换

转载 作者:太空狗 更新时间:2023-10-29 19:44:14 25 4
gpt4 key购买 nike

我有 C# 和 Java 的背景,我似乎无法理解在 C++ 中使用指针进行转换意味着什么。

例如:

int x = 1;
char c = *((char*)&x);

它有什么作用?它有什么用?

最佳答案

在您的两个示例中,您都犯了导致代码无法编译的错误。所以我假设您正在尝试执行以下操作:

int x = 1;
char c = *((char*)&x);

根据您的体系结构,c 现在将具有 x 的最低或最高有效字节的值。在此示例中,这将是 0 或 1(这实际上可用于检测字节顺序)。

您的第二个示例将不起作用,因为您试图忽略 const 导致非法操作/错误转换(这也称为“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();"

关于使用指针的 C++ 类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11708640/

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