C ++指向成员函数的指针继承 [英] C++ Pointers to Member Functions Inheritance

查看:156
本文介绍了C ++指向成员函数的指针继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要能够有一个超类执行由继承自它的类定义的回调。我对C ++比较陌生,从我可以告诉它看起来像成员函数指针的主题是一个非常阴暗的区域。

I have a need to be able to have a super class execute callbacks defined by a class that inherits from it. I am relatively new to C++ and from what I can tell it looks like the subject of member-function-pointers is a very murky area.

我已经看到了问题的答案和随机博客帖子讨论各种各样的事情,但我不知道他们是否专门处理我的问题在这里。

I have seen answers to questions and random blog posts that discuss all sorts of things, but I am not sure if any of them are specifically dealing with my question here.

这里是一个简单的代码块这说明我想做什么。这个例子可能没有什么意义,但它准确地类似于我试图写的代码。

Here is a simple chunk of code that illustrates what I am trying to do. The example might not make a lot of sense, but it accurately resembles the code I am trying to write.

class A {
    protected:
    void doSomething(void (A::*someCallback)(int a)) {
        (*this.*someCallback)(1234);
    }
};

class B : public A {
    public:
    void runDoIt() { doSomething(&B::doIt); }
    void runDoSomethingElse() { doSomething(&B::doSomethingElse); }
    protected:
    void doIt(int foo) {
        cout << "Do It! [" << foo << "]\n";
    }
    void doSomethingElse(int foo) {
        cout << "Do Something Else! [" << foo << "]\n";
    }
};

int main(int argc, char *argv[]) {
    B b;
    b.runDoIt();
    b.runDoSomethingElse();
}


推荐答案

,我建议你使用boost :: function为手头的任务。

If you can use boost libraries, I would suggest you use boost::function for the task at hand.

class A {
public:
   void doSomething( boost::function< void ( int ) > callback )
   {
      callback( 5 );
   }
};

然后任何继承(或外部类)都可以使用boost :: bind做调用:

Then any inheriting (or external class) can use boost::bind do make a call:

class B {
public:
   void my_method( int a );
};
void test()
{
   B b;
   A a;
   a.doSomething( boost::bind( &B::my_method, &b, _1 ) );
};

我没有检查确切的语法,我从顶部输入,至少接近正确的代码。

I have not checked the exact syntax and I have typed it from the top of my head, but that is at least close to the proper code.

这篇关于C ++指向成员函数的指针继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆