如何获取类成员函数指针

时间:2015-06-25 08:25:54

标签: c++ pointers

对于一个类,我想将一些函数指针存储到另一个类的成员函数中。我试图返回一个类成员函数指针。可能吗?

class one{
public:
  void x();
  void y();
};
typedef void(one::*PF)(void);

class two :public one{
public:
  virtual PF getOneMethodPointer();
};

class three : public two{
  std::vector<PF> pointer_to_function;
  PF getOneMethodPointer();
    pointer_to_function.push_back(getOneMethodPointer())? //how to get method x from class one?
};

2 个答案:

答案 0 :(得分:1)

它的C ++语法是:

class two: public one{
  virtual PF getOneMethodPointer(){
    return &one::x;
  }
};

[Live example]

答案 1 :(得分:1)

在C ++ 11/14中,您始终可以使用std::function包装器来避免编写不可读和旧的C风格函数指针。这是一个简单的程序:

#include <iostream>
#include <functional>

using namespace std;

class one {
public:
    void x() {  cout << "X called" << endl; }
    function<void()> getOneMethodPointer();
};

class two : public one {
public:
    function<void()> getOneMethodPointer() {
        return bind(&one::x, this);
    }
};

int main()
{
    two* t = new two();
    t->getOneMethodPointer()();
    delete t;
    return 0;
}

正如您所看到的,还有std::bind用于将方法绑定到std::function。第一个参数是对x()方法的引用,第二个参数指定指针指向哪个具体(实例化)对象。请注意,如果您对st::bind“嘿,x()类绑定我one方法”说,它仍然不知道它在哪里。它知道 - 例如 - 此对象中的x()方法可以在其开头旁边找到20个字节。只有当您添加它来自例如two* t;对象时,std::bind才能找到该方法。

编辑:在评论中回答您的问题:下面的代码显示了使用虚拟getMethodPointer()方法的示例:

#include <iostream>
#include <functional>

using namespace std;

class one {
public:
    void x() {  cout << "X called (bound in one class)" << endl; }
    void y() {  cout << "Y called (bound in two class)" << endl; }
    virtual function<void()> getMethodPointer() {
        return bind(&one::x, this);
    }
};

class two : public one {
public:
    virtual function<void()> getMethodPointer() {
        return bind(&one::y, this);
    }
};

int main()
{
    one* t_one = new one();
    one* t_two = new two();
    t_one->getMethodPointer()();
    t_two->getMethodPointer()();
    delete t_one;
    delete t_two;
    return 0;
}