使用 const char * const 将 void 指针传递给函数

aah*_*134 5 c++ pointers casting

好的,我有一个变量

void * vp

通过一个函数 proccessData (void * vp)

我有一个接受以下内容作为参数的函数

findIDType(const char* const pointer)并想将 pv 传递为findIDType(pv)

使用 GNU 2.95.3 编译

顺便说一句,不能使用任何其他编译器。

问题是编译器没有告诉我为什么它不可接受,它只是打印出一条消息,cannot没有任何有用的描述。

如何投射?从void*const char* const

我已经尝试过(char*)pv(const char*)pv(const char* const)pv没有运气

Ily*_*kiy 3

您必须使用reinterpret_cast, 并强制转换为您想要传递的完整类型,这应该有效:

const char* const ptrTpPass = reinterpret_cast<const char* const>(vp);
Run Code Online (Sandbox Code Playgroud)

但正如评论中提到的,static_cast也可以工作,而且实际上更好:

const char* const ptrTpPass = static_cast<const char* const>(vp);
Run Code Online (Sandbox Code Playgroud)

  • 从“void*”转换某些指针时,首选“static_cast”。事实上,在他的旧编译器中,“void*”可能不允许使用“reinterpret_cast”。[有关更多信息,请参阅此](http://stackoverflow.com/questions/310451/should-i-use-static-cast-or-reinterpret-cast-when-casting-a-void-to-whatever)。另外,在示例中使用“static_cast”在我的编译器(GCC4.8.1)上运行良好。 (2认同)