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

标签 c++ pointers

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

下面是一个示例和我收到的错误。执行此类操作的标准方法是什么?

嗯:

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

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

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

B.h:

#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;
}

主要.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::function
  3. boost::function

这真的取决于偏好和图书馆的选择。就个人而言,我大部分时间都使用 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;
};

关于c++ - 用函数指针初始化另一个类中的对象指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21566979/

相关文章:

c++ - 为什么我在这个简单的代码中得到 "ld: warning: direct access in _main to global weak symbol"?

c++ - 重新分配指针给出错误

C++ 运算符重载合成转换

c++ - mysql c++ 连接器在我插入数据库时​​减少了我的字符串

c++ - Qt5 如何将 qDebug() 语句重定向到 Qt Creator 2.6 控制台

c++ - 这个指针是指向给定对象还是指向给定对象的地址?

以指针为参数的c++函数问题

c++ - 面向 C++ 开发人员的 Python

C++ 函数返回指针不会造成段错误

c - 如何使用void*?