gpt4 book ai didi

c++ - 指向派生类的成员函数的指针,但不是派生(虚)函数

转载 作者:搜寻专家 更新时间:2023-10-31 01:33:28 27 4
gpt4 key购买 nike

我有一个特别的问题想要解决,我不确定是否可行,因为我找不到任何信息或正在完成的示例。基本上,我有:

class ParentObject {};

class DerivedObject : public ParentObject
{
void myFunction(){}
};

class OtherDerivedObject : public ParentObject
{
void myOtherFunction(){}
};

并想要一个指向 ParentObject::* 的函数指针,并让它能够从任一派生类中获取函数。我想这样做的原因,我还有一个类(class)

class functionRegistry
{
std::map<string, *functionPoint> functionMap;
}

每个对象(理想情况下在 ParentObject 中,但如有必要,可以在派生对象中单独执行)都有一个 functionRegistry 实例,我需要 functionPoint 能够指向 DerivedObject 或 OtherDerivedObject 类型对象中的函数。

提前致谢

最佳答案

您只需要一个 static_cast 来用正确的类型填充 map 。

using pfunc_type = void (ParentObject::*)() ;
pfunc_type pfunc1 = static_cast<pfunc_type>(&DerivedObject::myFunction);

因为这是标准允许的:

[expr.static.cast/12] - §5.2.9¶12

A prvalue of type “pointer to member of D of type cv1 T” can be converted to a prvalue of type “pointer to member of B of type cv2 T”, where B is a base class (Clause [class.derived]) of D, if cv2 is the same cv-qualification as, or greater cv-qualification than, cv1.72 If no valid standard conversion from “pointer to member of B of type T” to “pointer to member of D of type T” exists ([conv.mem]), the program is ill-formed. The null member pointer value ([conv.mem]) is converted to the null member pointer value of the destination type. If class B contains the original member, or is a base or derived class of the class containing the original member, the resulting pointer to member points to the original member. Otherwise, the behavior is undefined. [ Note: although class B need not contain the original member, the dynamic type of the object with which indirection through the pointer to member is performed must contain the original member; see [expr.mptr.oper]. — end note ]

但是虽然这是允许的,但您必须非常小心地确保将指针应用于具有正确动态类型的对象上的成员。

关于c++ - 指向派生类的成员函数的指针,但不是派生(虚)函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41347826/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com