本文介绍了C++ 类型转换:将指针从 void 指针转换为类指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将指向 void 对象的指针转换为类对象?
How to cast a pointer to void object to class object?
推荐答案
使用 static_cast
.请注意,只有在指针确实指向指定类型的对象时才必须这样做;也就是说,指向 void
的指针的值取自指向此类对象的指针.
With a static_cast
. Note that you must only do this if the pointer really does point to an object of the specified type; that is, the value of the pointer to void
was taken from a pointer to such an object.
thing * p = whatever(); // pointer to object
void * pv = p; // pointer to void
thing * p2 = static_cast<thing *>(pv); // pointer to the same object
如果您发现自己需要这样做,您可能需要重新考虑您的设计.您正在放弃类型安全,从而很容易编写无效代码:
If you find yourself needing to do this, you may want to rethink your design. You're giving up type safety, making it easy to write invalid code:
something_else * q = static_cast<something_else *>(pv);
q->do_something(); // BOOM! undefined behaviour.
这篇关于C++ 类型转换:将指针从 void 指针转换为类指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!