将类指针指向空指针

编程入门 行业动态 更新时间:2024-10-21 15:30:10
本文介绍了将类指针指向空指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我如何能够将一个类指针转换为一个通用指针,如void *?这个代码有效吗?

How can I able to cast a class pointer to a generic pointer like void*? Like is this code valid?,

class CFoo { int a; public: CFoo():a(1){} ~CFoo(){} getNum(){return a;} }; void tfunc(void* data) { CFoo* foo = static_cast<CFoo*>(data); std::cout << "Number: " << foo->getNum(); delete foo; } int main() { CFoo* foo = new CFoo; void* dt = static_cast<void*>(foo); tfunc(dt); // or tfunc(static_cast<void*>(food)); return 0; }

推荐答案

以下是标准对此的说明:

This is perfectly valid. Here is what standard has to say about it:

§4.10指针转换

§4.10 Pointer conversions

2指向 cv T 的类型的右值,其中 T 是一个对象类型,可以转换为指向 cv 类型的右值 void 。将指向 cv T 的指针转换为指针到 cv void 指向类型为 T 的对象所在的存储位置的开始,是类型 T (即不是基类子对象)的最导出的对象(1.8)。

2 An rvalue of type "pointer to cv T," where T is an object type, can be converted to an rvalue of type "pointer to cv void." The result of converting a "pointer to cv T" to a "pointer to cv void" points to the start of the storage location where the object of type T resides, as if the object is a most derived object (1.8) of type T (that is, not a base class subobject).

这意味着您可以将指针转换为void指针。 ...

which means you can convert your pointer to class to a void pointer. And ...

§5.2.9静态投放

§5.2.9 Static cast

10可以显式地将转换为指向对象类型的指针的类型指向 cv void 将类型指针的值转换为指向 cv void 并返回原始指针类型将具有其原始值。

10 An rvalue of type "pointer to cv void" can be explicitly converted to a pointer to object type. A value of type pointer to object converted to "pointer to cv void" and back to the original pointer type will have its original value.

这意味着您可以使用 static_cast 将一个void指针转换回一个原始类指针。

which means you can use static_cast to convert a void pointer back to an original class pointer.

希望它有帮助。祝你好运!

Hope it helps. Good Luck!

更多推荐

将类指针指向空指针

本文发布于:2023-07-29 00:46:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1235678.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:指针

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!