误解的函数指针-将其作为参数传递 [英] Misunderstanding function pointer - passing it as an argument

查看:107
本文介绍了误解的函数指针-将其作为参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过一个函数指针作为参数将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:

无法在初始化时转换int (A::*)(int)' to int(*)(int)'

cannot convert int (A::*)(int)' toint (*)(int)' in initialization

首先,我要它进行编译.
其次,我不希望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);
}

这篇关于误解的函数指针-将其作为参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆