c++ - 在 C++ 中,是否允许将函数指针转换为一个函数指针,该函数指针作为参数获取一个指向基类或派生类的指针?

标签 c++ pointers casting function-pointers

以下是否会按预期工作?

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/

相关文章:

c++ - 骑士之旅。选择容器

c++ - 将 argc 和 argv 传递给 QApplication 进入单元测试用例方法

c++ - udp源端口和目的端口必须匹配吗?

c++ - 跟踪 QTabWidget 中的可移动选项卡

c - 我的程序在某些情况下似乎无法分隔单词

c - 如何声明指向文件的动态指针数组

c - 增加 vector 地址并将其分配给指针

mysql - 我可以在不破坏 INDEX 的情况下将 VARCHAR 转换为 INT 吗?

c++ - 是否存在将 double 转换为 long long 的优雅方法?

python - 如何将 `Object` 与字符串连接起来?