如何将指向方法的指针作为参数传递? [英] How to pass a pointer to method as a parameter?

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

问题描述

我想将方法​​作为参数传递给采用int并返回void的方法:

  void A :: SetCallback(void(* callback)(int)){.....................}无效B :: test(){a-> SetCallback(& B :: Done);//}无效B :: Done(int i){....................................} 

test()内部,我收到此错误:

 错误1错误C2664:无法将参数1从'void(__thiscall B :: *)(int)'转换为'void(__cdecl *)(int)' 

我在StackOverflow上看到了一些如何解决此问题的示例,但它使用了我无法访问的C ++ 11中的元素.
如何使用C ++ 03修复此问题?

解决方案

您不能将非静态方法传递给采用函数指针的函数.函数和方法是完全不同的两件事.显然,要调用非静态方法,必须有一个要调用其方法的对象.

如果在您的示例中, Done()是静态类方法,那么可以,您可以通过这种方式传递它,因为静态类方法只是函数的另一个名称./p>

可能有一个指向类方法的指针:

  void A :: SetCallback(void(B :: * callback)(int)){}无效B :: test(){a-> SetCallback(& B :: Done);//}无效B :: Done(int i){....................................} 

但是要调用类方法,您需要一个对象,该对象的方法要调用:

  B * object = give_me_a_pointer_to_b_from_somewhere();(object-> * callback)(0); 

I want to pass a method as an argument to a method which takes an int and returns void:

void A::SetCallback(void (*callback)(int))
{
   .....................
}

void B::test()
{
   a->SetCallback(&B::Done); //
}

void B::Done(int i)
{
   ..........................
}

Inside test() I get this error:

Error   1   error C2664: cannot convert parameter 1 from 'void (__thiscall B::* )(int)' to 'void (__cdecl *)(int)'

I saw some example on StackOverflow how to fix this but it uses elements from C++11, to which I do not have access.
How can I fix this using C++03 ?

解决方案

You cannot pass a non-static method to a function that takes a pointer to a function. Functions and methods are two completely different things. In order to invoke a non-static method you have to, obviously, have an object whose method you're invoking.

If, in your example, Done() is a static class method, then, yes, you can pass it this way, since a static class method is just another name for a function.

It is possible to have a pointer to a class method:

void A::SetCallback(void (B::*callback)(int))
{

}

void B::test()
{
   a->SetCallback(&B::Done); //
}

void B::Done(int i)
{
   ..........................
}

But in order to invoke the class method, you need an object whose method to invoke:

B *object=give_me_a_pointer_to_b_from_somewhere();

(object->*callback)(0);

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

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