大家好:)我的函数指针有问题
我的“回调”函数参数是:
1)像这样的函数:int(* fx)(int,int)
2)一个int变量:int a
3)另一个int:int b
好吧,问题在于我要传递给“回调”的函数是一个非静态函数成员:(并且有很多问题,
如果比我更聪明的人有一些时间可以花,他可以看一下我的代码:)
#include <iostream>
using namespace std;
class A{
private:
int x;
public:
A(int elem){
x = elem;
}
static int add(int a, int b){
return a + b;
}
int sub(int a, int b){
return x - (a + b);
}
};
void callback( int(*fx)(int, int), int a, int b)
{
cout << "Value of the callback: " << fx(a, b) << endl;
}
int main()
{
A obj(5);
//PASSING A POINTER TO A STATIC MEMBER FUNCTION -- WORKS!!
// output = 'Value of the callback: 30'
callback(A::add, 10, 20);
//USING A POINTER TO A NON-STATIC MEMBER FUNCTION -- WORKS!!
int(A::*function1)(int, int) = &A::sub;
// output = 'Non static member: 3'
cout << "Non static member: " << (obj.*function1)(1, 1) << endl;
//PASSING A POINTER TO A NON-STATIC MEMBER FUNCTION -- aargh
// fallita! tutto quello sotto non funziona --> usa i funtori???
// puoi creare una classe wrapper ma non riuscirai mai a chiamare da callback
int(A::*function2)(int, int) = &A::sub;
int(*function3)(int, int) = obj.*function2; //[error] invalid use of non-static member function
callback(function3, 1, 1);
}
有一种方法可以尝试编写指针,例如int(* fx)(int,int)=某些东西?
我进行了很多搜索,但没有人能给我答案(嗯,有一个答案:“不”,但我仍然认为我可以做点什么)
我也听说过函子,在这种情况下它们可以帮助我吗?
感谢任何人
PS:对不起,我的英语不好
EDIT1:我可以这样使用:
template <class T>
void callback2( T* obj, int(T::*fx)(int, int), int a, int b)
{
cout << "Value of the callback: " << (obj->*fx)(a, b) << endl;
}
void callback2( void* nullpointer, int(*fx)(int, int), int a, int b)
{
cout << "Value of the callback: " << fx(a, b) << endl;
}
而在我的主要:
callback2(NULL, &mul, 5, 3); // generic function, it's like: int mul(int a, int b){return a*b;}
callback2(NULL, &A::add, 5, 3); //static member function
callback2(&obj, &A::sub, 1, 1); //non static member function
我并不完全满意,因为我不想将第一个参数(对象)传递给我的“ callback2” ...
对于不理解我(糟糕)解释的人来说,问题是:我可以删除我的callback2函数中的第一个参数?
原型将是
void callback2(int(*fx)(int, int), int a, int b)<br>
我会这样称呼:
callback2(&obj.sub, 1, 3);
无法通过这种方式引用函数:
int (*function3)(int, int) = obj.*function2;
您必须像这样传递函数的地址:
int (*function3)(int, int) = std::mem_fn(&A::sub, obj); // ^^^^^^^^^^^^^^^^^^^^^^^^^
该表达式function2
衰减为指向函数的指针,该指针使其可以工作。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句