c++ - 具有不同返回类型的函数指针

标签 c++ c

这是正确的代码吗?

class SomeClass;

SomeClass* createSomeClass(); // just returns new SomeClass
void* (*createFuncPtr)();

int main()
{
    createFuncPtr= (void* (*)()) &createSomeClass;
    SomeClass* instance = (SomeClass*)createFuncPtr();
}

C 标准说:

768 If a converted pointer is used to call a function whose type is not compatible with the pointed-to type, the behavior is undefined.

在这种情况下,函数类型是否兼容?或者如果我想避免 ant 类的麻烦,我是否必须在调用它之前重新转换函数指针?

SomeClass* instance = ((SomeClass* (*)())createFuncPtr)();

谢谢!

编辑:是的,它包含 C++ 代码,但如果它只是 C,我的问题仍然有效,请留下 C 标签。

最佳答案

来自 C99 标准部分 6.7.5.1,第 2 段:

For two pointer types to be compatible, both shall be identically qualified and both shall be pointers to compatible types.

在您的情况下,函数指针不兼容,因为返回值不兼容。所以,是的,您必须在调用指向的函数之前回退。

关于c++ - 具有不同返回类型的函数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22782166/

相关文章:

android - 使用 NDK 显示轮廓的图像处理

c++ - 如果在多个共享库中调用并且启用了libstdc++静态链接,则C++流变得很糟糕

c++ - OpenGL VBO 数据似乎已损坏

c - C中简单文本文件行计数器的问题

c++ - 什么时候数据类型对编译器的意义大于其存储空间?

c - 设备驱动程序编程 - USB

python - 如何仅将 swig 与已编译的 dll 和头文件一起使用

c++ - 如何在 C++ 中检索基类的类型?

c - 将源文件与目标文件一起编译是否正确?

c - 什么取代了 libbluetooth1-dev 以使用 BlueZ 进行 C 编程?