指向成员函数的指针 [英] Pointer to a member-function
问题描述
我想做以下事情:
我有两个类,A和B,并且想绑定一个函数从A到B的函数,所以每当有人调用B的函数,函数从A被调用。
I would like to do the following: I have two classes, A and B, and want to bind a function from A to a function from B so that whenever something calls the function in B, the function from A is called.
基本上,这是场景:
( important A和B应该是独立的类)
So basically, this is the scenario: (important A and B should be independent classes)
这将是A类:
class A {
private:
// some needed variables for "doStuff"
public:
void doStuff(int param1, float *param2);
}
这是B类
class B {
private:
void callTheFunction();
public:
void setTheFunction();
}
这是我想要使用这些类:
And this is how I would like to work with these classes:
B *b = new B();
A *a = new A();
b->setTheFunction(a->doStuff); // obviously not working :(
我读过,这可以通过std :: function ,这将如何工作?此外,这是否会影响性能每当 callTheFunction()
被调用?在我的示例中,它的一个音频回调函数,应该调用
I've read that this could be achieved with std::function, how would this work? Also, does this have an impact in the performance whenever callTheFunction()
is called? In my example, its a audio-callback function which should call the sample-generating function of another class.
推荐答案
基于用法的解决方案C ++ 11 std :: function和std :: bind 。
Solution based on usage C++11 std::function and std::bind.
#include <functional>
#include <stdlib.h>
#include <iostream>
using functionType = std::function <void (int, float *)>;
class A
{
public:
void doStuff (int param1, float * param2)
{
std::cout << param1 << " " << (param2 ? * param2 : 0.0f) << std::endl;
};
};
class B
{
public:
void callTheFunction ()
{
function (i, f);
};
void setTheFunction (const functionType specificFunction)
{
function = specificFunction;
};
functionType function {};
int i {0};
float * f {nullptr};
};
int main (int argc, char * argv [])
{
using std::placeholders::_1;
using std::placeholders::_2;
A a;
B b;
b.setTheFunction (std::bind (& A::doStuff, & a, _1, _2) );
b.callTheFunction ();
b.i = 42;
b.f = new float {7.0f};
b.callTheFunction ();
delete b.f;
return EXIT_SUCCESS;
}
编译:
$ g ++ func.cpp -std = c ++ 11 -o func
$ g++ func.cpp -std=c++11 -o func
输出: p>
Output:
$ ./func
$ ./func
0 0
42 7
这篇关于指向成员函数的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!