我有一个想要解决的特定问题,我不确定是否可能,因为我找不到任何信息或正在完成的示例。 基本上,我有:
class ParentObject {};
class DerivedObject : public ParentObject
{
void myFunction(){}
};
class OtherDerivedObject : public ParentObject
{
void myOtherFunction(){}
};
并且想要一个指向 ParentObject::* 的函数指针,并让它能够从任一派生类中获取函数。 我想这样做的原因是,我还有另一门课
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/