简体   繁体   English

转换为无效*

[英]Convert into void*

how can I convert any object of my own class convert into pointer to void?如何将我自己的 class 中的任何 object 转换为指向 void 的指针?

MyClass obj;
(void*)obj; // Fail
MyClass obj;
void *p;

p = (void*)&obj; // Explicit cast.
// or:
p = &obj; // Implicit cast, as every pointer is compatible with void *

But beware !但要小心! obj is allocated on the stack this way, as soon as you leave the function the pointer becomes invalid. obj以这种方式在堆栈上分配,一旦您离开 function,指针就会失效。

Edit : Updated to show that in this case an explicit cast is not necessary since every pointer is compatible with a void pointer.编辑:更新以表明在这种情况下不需要显式转换,因为每个指针都与 void 指针兼容。

If you use the address, you can convert it to a void pointer.如果使用地址,可以将其转换为void指针。

MyClass obj;
void *ptr = (void*)&obj; // Success!

You cant convert a non-pointer to void* .您不能将非指针转换为void* You need to convert the pointer to your object to void*您需要将指向 object 的指针转换为void*

(void*)(&obj); //no need to cast explicitly.

that conversion is implicit这种转换是隐含的

void* p = &obj; //OK

To do something which has any chance of being meaningful, first you have to take the address of an object, obtaining a pointer value;要做一些有意义的事情,首先你必须获取一个 object 的地址,获得一个指针值; then cast the pointer.然后投射指针。

MyClass obj;
MyClass * pObj = &obj;
void * pVoidObj = (void*)pObj;

i beleive you could only convert a pointer to an object to a pointer to void???我相信你只能将指向 object 的指针转换为指向 void 的指针???

Perhaps: (void*)(&obj)也许: (void*)(&obj)

In addition to the technical answers: Assert, that you avoid multiple inheritance or else you don't assign the address of super-class interfaces to a void*, for they will not be unique.除了技术答案:断言,您避免使用多个 inheritance,否则您不会将超类接口的地址分配给 void*,因为它们不是唯一的。 Eg例如

class S1 { int u; };
class S2 { int v; };
class MyClass : public S1, public S2 {};

MyClass obj;
S2* s2 = &obj;
void * p1 = &obj;
void * p2 = s2;

Here p1 and p2 (==s2) will be different, because the S2 instance in C has an address offset.这里p1和p2(==s2)会不一样,因为C中的S2实例有地址偏移。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM