这是正确的代码吗?
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/