简体   繁体   English

保存指向派生类的成员函数的指针

[英]Save a pointer to member function of derived class

I am looking for a way to save a pointer to a member function of a derived class. 我正在寻找一种保存指向派生类的成员函数的指针的方法。

For exemple: 举个例子:

class A
{
public:
    typedef void (A::*FunctionP) (int a);
};

class B : A 
{
public:
    void Test(int a)
    {
        //Do stuff
    }
    B()
    {
        FunctionP theFunc = &B::Test;
    }

};

The following code dose not compile.. Is there another way to do this? 以下代码无法编译。还有另一种方法吗? (Using template's maybe, or boost) (可能使用模板,也可以使用boost)

(Btw class A is an abstract class witch one of its implementations is invoking functions saved as FunctionP) (Btw类A是一个抽象类,其实现之一是调用另存为FunctionP的函数)

Thank you 谢谢

Just use a static_cast : 只需使用static_cast

FunctionP theFunc = static_cast<FunctionP>(&B::Test);

Coliru: http://coliru.stacked-crooked.com/a/2cfed4926aed43db Coliru: http ://coliru.stacked-crooked.com/a/2cfed4926aed43db

Still, it might be even better to use std::function and std::bind , depending on your needs. 不过,根据您的需求,最好使用std::functionstd::bind

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将派生类中的成员函数的指针强制转换为抽象成员函数的指针 - cast a pointer to member function in derived class to a pointer to abstract member function 关于派生类的成员函数的指针 - About pointer to member function of derived class 指向派生类成员函数的指针,但不指向派生(虚拟)函数 - Pointer to member function of derived class, but not derived(virtual) function 是否可以保存从基类使用的另一个类中派生的指向函数成员的指针 - Is it possible to save pointer to function member from a derived in another class used by a base class 使用基类函数指针访问派生类成员函数 - Using base class function pointer to access derived class member function 如何注册派生的 class 成员 function 指针与基数 class - How to register a derived class member function pointer with a base class 在派生类的对象上使用指向基类的成员函数的指针 - Using pointer to member function of a base class on object of derived class 函数在派生类中但不在基类中,指向基类的指针--&gt;“不是成员”错误 - function in derived but not in base class, pointer to base --> "not a member" error 成员函数指针转换,从派生类到基类 - Member function pointer cast, from Derived to Base class 如何基于派生类的指针找到成员函数? - How is a member function found based on this pointer of the derived class?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM