没有使用函数指针参数的隐式向上转换?

No implicit upcasting with function pointers arguments?

这是我 运行 遇到的一种奇怪情况。我希望指针隐式向上转换:

struct BaseClass
{};

struct DerivedClass : BaseClass
{};

void baseClassArgFunc(BaseClass* arg) {}            // Function taking BaseClass argument
void derivedClassArgFunc(DerivedClass* arg) {}      // Function taking DerivedClass argument

int main()
{
    void (*pBaseFuncArg) (BaseClass*);      // Pointer to function taking BaseClass argument
    void (*pDerivedFuncArg) (DerivedClass*);    // Pointer to function taking DerivedClass argument

    pBaseFuncArg = baseClassArgFunc;            // Assign pointer, works fine
    pDerivedFuncArg = derivedClassArgFunc;      // Assign pointer, works fine

    pBaseFuncArg = derivedClassArgFunc;         // A value of type void (*) (DerivedClass *arg) cannot be 
                                                // assigned to an entity of type void (*) (BaseClass *)

    pDerivedFuncArg = baseClassArgFunc;         // A value of type void (*) (BaseClass *arg) cannot be 
                                                // assigned to an entity of type void (*) (DerivedClass *)

    return 0;
}

我希望将 void ( * ) (DerivedClass*) 分配给 void baseClassArgFunc(BaseClass* arg) 是安全的。我很困惑。我想那时候函数指针参数没有隐式向上转换?

更改您的 类 以暴露问题:

struct BaseClass
{
};

struct DerivedClass : BaseClass
{
    int a;
};

然后

pBaseFuncArg = derivedClassArgFunc;

不安全:

 void derivedClassArgFunc(DerivedClass* arg) { arg->a = 42; }


 int main()
 {
     void (*pBaseFuncArg) (BaseClass*) = derivedClassArgFunc;
     BaseClass base;

     //derivedClassArgFunc(&base); // Doesn't compile as expected
     pBaseFuncArg(&base);          // Would be UB, base->i won't exist
 }