繁体   English   中英

使用函数指针初始化另一个类中的对象指针

[英]Initialize object pointer in another class with function pointer

考虑以下。 A具有一个函数指针作为成员,并在其构造函数中接受一个函数以传递给该成员。 在一个单独的文件中,我有一个类B ,其中包含一个指向类A的指针作为成员,而类B还具有要传递给类A的函数作为成员。

以下是一个示例以及我收到的错误。 做这样的事情的标准方法是什么?

啊:

class A {
 private:
  int (*func)(int);

 public:
  A(int (*func_)(int));
};

A::A(int (*func_)(int)) : func(func_) {}

BH:

#include "A.h"  // Why can't I forward declare A instead?

class B {
 private:
  A *A_ptr;
  int function(int);  // some function

 public:
  B();
  ~B();
};

int B::function(int n) {
  return n+2;  // some return value
}

B::B() {
  A_ptr = new A(function);
}

B::~B() {
  delete A_ptr;
}

main.cpp中:

#include "B.h"

int main() {
  B b;
}

我得到的错误:

B.h: In constructor ‘B::B()’:
B.h:18:25: error: no matching function for call to ‘A::A(<unresolved overloaded function type>)’
B.h:18:25: note: candidates are:
A.h:9:1: note: A::A(int (*)(int))
A.h:9:1: note:   no known conversion for argument 1 from ‘<unresolved overloaded function type>’ to ‘int (*)(int)’
A.h:1:7: note: A::A(const A&)
A.h:1:7: note:   no known conversion for argument 1 from ‘<unresolved overloaded function type>’ to ‘const A&’

要回答有关“执行此操作的标准方法是什么”的问题,我假设您的意思是传递成员函数和/或常规函数指针,并用一些数据执行它们。 提供此功能的一些流行实现是:

  1. FastDelegate
  2. 的std ::功能
  3. 提振::函数

这实际上归结为偏好和库选择。 就个人而言,我大多数时候都使用FastDelegate,然后使用std :: function。

我发布的所有链接都应具有教程信息,以使您入门和运行,并向您展示如何轻松地正确传递和存储成员函数和/或常规函数指针。

这是在示例中使用FastDelegate的示例:

class A 
{
public:
    // [1] This creates a delegate type. Can used for any function, 
    // class function, static function, that takes one int 
    // and has a return type of an int.
    typedef FastDelegate1< int, int > Delegate;

    // [2] Pass the delegate into 'A' and save a copy of it.
    A( const Delegate& delegate ) : _delegate( delegate ) { };

    void execute()
    {
        // [7]
        // Result should be 10!
        int result = _delegate( 8 ); 
    }

private:
    // [3] Storage to save the Delegate in A.
    Delegate _delegate;
};

class B
{
public:
    B() 
    {
        // [4] Create the delegate
        A::Delegate bDelegate;
        bDelegate.bind( this, &B::function );

        // [5] Create 'A' passing in the delegate.            
        _aPtr = new A( bDelegate );

        // [6] Test it out!! :) 
        // This causes `A` to execute the Delegate which calls B::function. 
        _aPtr->execute();
    }

    ~B() 
    {
        delete _aPtr; 
    }

    int function( int n )
    {
        return n+2;
    }

private:
    A* _aPtr;
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM