本文介绍了子类方法指针以法父参数C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是陌生的什么,我想看看,我会试图澄清尽可能。我使用的是在Ubuntu 14.04和C ++ 11 GCC 4.8。

it might be strange what i'm trying to see and i will try to clarify as much as possible. I'm using gcc 4.8 on ubuntu 14.04 and C++11.

我想试图做的是:


  • 请A类

  • 请在A级它获取作为参数的函数

  • 一个指向同一个类中的一个成员

  • 请新的B类从A继承

  • 请B级的新方法

  • 给一个指向类B的方法作为参数父类A的方法

  • make a class A
  • make a function in that class A which gets as argument
  • a pointer to a class member of the same class
  • make a new class B which inherits from A
  • make a new method of class B
  • give a pointer to that method of class B to a method of parentclass A as argument

class A{
    typedef void(A::*METHOD);        

    void executeMethod(METHOD arg){};
}

class B : A{

    void sampleMethod(){};

    void childMethod(){              

      this->executeMethod(&B::sampleMethod); //<== error
    }
}


然而,这使我在$ C $的cblock以下错误:

However this brings me the following error in codeblocks:

error: no matching function to call for 'B::executeMethod(void B::*)'

有没有解决这个办法吗?
还有什么我需要做的,说清楚你的,就是我要完成的?

Is there any way around this?Is there anything else i need to do to make it clear to you, what i'm trying to accomplish?

推荐答案

您不能直接调用方法,孩子从基类,但可以使用的模板:

You cannot directly call child method from a base class, but you can use template:

class A {
public:
    template<class T>
    void executeMethod( void (T::*method)() )
    {
        (static_cast<T *>( this )->*method)();
    }
};

class B : public A {
public:
    void sampleMethod() {}
    void childMethod() { executeMethod( &B::sampleMethod ); }
};

但更灵活的解​​决方案是使用的std ::功能的std ::绑定为那么你就可以传方法这签名不匹配。

But more flexible solution would be to use std::function and std::bind as then you can pass methods which signature does not match.

class A {
public:
    typedef std::function<void()> Method;

    void executeMethod( const Method &method )
    {
        method();
    }
};

class B : public A {
public:
    void sampleMethod1() {}
    void sampleMethod2( int param ) {}

    void childMethod1() { executeMethod( std::bind( &B::sampleMethod1, this ); }
    void childMethod2() { executeMethod( std::bind( &B::sampleMethod2, this, 123 ); }
};

这篇关于子类方法指针以法父参数C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-26 22:49