请考虑以下事项。类 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&’
最佳答案
为了回答您关于“做这样的事情的标准方法是什么”的问题,我假设您的意思是传递成员函数和/或通用函数指针并使用一些数据执行它们。提供此功能的一些流行实现是:
这真的取决于偏好和图书馆的选择。就个人而言,我大部分时间都使用 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/