gpt4 book ai didi

c++ - 指向方法父参数的子类方法指针 C++

转载 作者:太空狗 更新时间:2023-10-29 20:12:18 24 4
gpt4 key购买 nike

我试图看到的内容可能很奇怪,我会尽量澄清。我在 ubuntu 14.04 和 C++11 上使用 gcc 4.8。

我想做的是:

  • 做一个A类
  • 在类 A 中创建一个函数作为参数
  • 指向同一类的类成员的指针
  • 创建一个继承自A的新类B
  • 创建B类的新方法
  • 将指向类 B 的方法的指针作为参数传递给父类 A 的方法

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

    void executeMethod(METHOD arg){};
    }

    class B : A{

    void sampleMethod(){};

    void childMethod(){

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

然而,这给我带来了代码块中的以下错误:

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

有什么办法解决这个问题吗?我还需要做些什么来向您说明我正在努力实现的目标吗?

最佳答案

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

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::functionstd::bind,因为这样您就可以传递签名不匹配的方法。

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++ - 指向方法父参数的子类方法指针 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28568543/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com