首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何获取类成员函数指针

如何获取类成员函数指针
EN

Stack Overflow用户
提问于 2015-06-25 08:25:54
回答 2查看 282关注 0票数 0

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

代码语言:javascript
复制
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?
};
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-06-25 09:47:42

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

代码语言:javascript
复制
#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::bindstd::function。第一个参数是对x()方法的引用,第二个参数指定指针要指向哪个具体(实例化)对象。注意,如果您对st::bind说“嘿,从one类绑定我x()方法”,它仍然不知道它在哪里。它知道,例如,这个对象中的x()方法可以在其开头处找到20个字节。只有当添加它来自例如two* t;对象时,std::bind才能够定位该方法。

编辑:在注释中回答您的问题:下面的代码展示了一个使用虚拟getMethodPointer()方法的示例:

代码语言:javascript
复制
#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;
}
票数 1
EN

Stack Overflow用户

发布于 2015-06-25 08:32:39

它的C++语法如下:

代码语言:javascript
复制
class two: public one{
  virtual PF getOneMethodPointer(){
    return &one::x;
  }
};

[实例]

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31044971

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档