C ++类型转换带指针 [英] C++ type casting with pointers
问题描述
我来自C#和Java的背景,我似乎不明白在C ++中用指针表示什么意思。
I come from a background of C# and Java and I can't seem to understand what casting with pointers means in C++.
例如:
int x = 1;
char c = *((char*)&x);
它做什么?它是什么有用的?
What does it do? What it is useful for?
推荐答案
在你的例子中,你犯错误使代码不编译。因此,我假设您尝试执行以下操作:
In both your examples you're making mistakes making the code not compile. So I'll assume you're trying to do the following:
int x = 1;
char c = *((char*)&x);
根据您的架构, c
具有 x
的最小或最高有效字节的值。在这个例子中,这将是0或1(这实际上可以用于检测字节排序)。
Depending on your architecture, c
will now have either the value of the least or the most significant byte of x
. In this example this would be either 0 or 1 (this can actually be used to detect the byte ordering).
你的第二个例子将不工作,因为你试图忽略 const
导致非法操作/错误转换(这也称为const正确性)。
Your second example won't work, cause you're trying to ignore the const
resulting in an illegal operation/bad cast (this is also called "const correctness").
编辑:关于您对这是什么意思?的评论:
Regarding your comment about "what does it mean?":
在表达式中:
& somevariable
将返回 somevariable
的地址。
* somevariable
将假设 somevariable
的内容是实际值的地址, 。
In expressions:
&somevariable
will return the address of somevariable
.
*somevariable
will assume the contents of somevariable
are the address of the actual value, which is then returned.
在声明中:
datatype
是正常变量/对象。这是通过按值。
datatype&
是引用。这与Java / C#中的正常变量完全相同,并通过引用传递。
datatype *
是一个指针。
In declarations:
datatype
is a normal variable/object. This is passed "by value".
datatype&
is a reference. This works exactly like normal variables in Java/C# and is passed by reference.
datatype*
is a pointer. This just contains the address where the actual value is located (see above) and is essentially passed by reference as well.
实际的转换工作与Java / C#非常相似,但指针就是这样:它们指向实际值的位置。虽然这可能会让你困惑,C / C ++中的指针与Java / C#中使用的标准变量/引用非常相似。
Actual casts work pretty much similar to Java/C#, but pointers are just that: They point to the location of the actual value. While this might confuse you, pointers in C/C++ work pretty much like the standard variables/references used in 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 ++类型转换带指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!