问题描述
我想通过一个函数指针作为参数将A类的成员函数传递给B类.请告知这条路是否通往某处,并帮助我填补坑洼.
I want to pass a member function of class A to class B via a function pointer as argument. Please advise whether this road is leading somewhere and help me fill the pothole.
#include <iostream>
using namespace std;
class A{
public:
int dosomeA(int x){
cout<< "doing some A to "<<x <<endl;
return(0);
}
};
class B{
public:
B(int (*ptr)(int)){ptr(0);};
};
int main()
{
A a;
int (*APtr)(int)=&A::dosomeA;
B b(APtr);
return 0;
}
这段出色的代码让我陷入了编译器错误:
This brilliant piece of code leaves me with the compiler error:
首先,我要它进行编译.
其次,我不希望dosomeA处于静态状态.
Firstly I want it to compile.
Secondly I don't want dosomeA to be STATIC.
推荐答案
指向成员的指针与普通函数指针不同.由于编译器错误指示&A::dosomeA
的类型实际上是int (A::*)(int)
而不是int (*)(int)
.
Pointers to members are different from normal function pointers. As the compiler error indicates the type of &A::dosomeA
is actually int (A::*)(int)
and not int (*)(int)
.
在B
的构造函数中,您需要一个A
实例,以使用.*
或->*
运算符之一来调用该成员.
Inside B
's constructor you need an instance of A
to call the member on using one the .*
or ->*
operators.
E.g'
B(int(A::*ptr)(int))
{
A atmp;
(atmp.*ptr)(int);
}
这篇关于误解的函数指针-将其作为参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!