以下是否会按预期工作?
struct A {};
struct B: public A {
int x;
};
void f( B* o ) {
std::cout << o->x << std::endl;
}
int main () {
B b;
b.x = 5;
reinterpret_cast<void(*)(A*)>(f)( &b );
}
最佳答案
强制转换后使用此类指针的未定义行为:
Any pointer to function can be converted to a pointer to a different function type. Calling the function through a pointer to a different function type is undefined, but converting such pointer back to pointer to the original function type yields the pointer to the original function.
来自 http://en.cppreference.com/w/cpp/language
所以你的问题的答案实际上是肯定的——你可以施法,但仅此而已。
您可能会问“只进行转换有什么意义?” - 当您想在单个集合中存储各种函数时,这很有用。
关于c++ - 在 C++ 中,是否允许将函数指针转换为一个函数指针,该函数指针作为参数获取一个指向基类或派生类的指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37606648/