[英]Get pointer to member function from within member function in C++
Currently in the program I am attempting to write I need to be able to get a pointer to a member function within a member function of the same class. 目前,我正在尝试编写程序,我需要能够获得指向同一类的成员函数中的成员函数的指针。 The pointer needs to be passed to a function as a void (*)().
指针需要作为void(*)()传递给函数。 Example:
例:
//CallFunc takes a void (*)() argument
class testClass {
public:
void aFunc2;
void aFunc1;
}
void testClass:aFunc2(){
callFunc(this.*aFunc1); // How should this be done?
}
void testClass:aFunc1(){
int someVariable = 1;
}
I'm trying to do this in GCC 4.0.1. 我正在尝试在GCC 4.0.1中执行此操作。 Also, the member function being called can't be static because it references non-static variables in the class that it is part of.
另外,被调用的成员函数不能是静态的,因为它引用了它所属的类中的非静态变量。 (In case you are wondering, the specific instance in which I need this is where I need to be able to pass a member function of a class to the GLUT function glutDisplayFunc() )
(如果您想知道,我需要在其中的特定实例是我需要能够将类的成员函数传递给GLUT函数glutDisplayFunc()的地方)
I read this article once and found it very interesting: 我阅读了这篇文章,发现它非常有趣:
http://www.codeproject.com/KB/cpp/FastDelegate.aspx http://www.codeproject.com/KB/cpp/FastDelegate.aspx
Also, for a FAQ about pointer to member functions, read this: 另外,有关成员函数指针的常见问题,请阅读以下内容:
http://www.parashift.com/c++-faq-lite/pointers-to-members.html http://www.parashift.com/c++-faq-lite/pointers-to-members.html
To take pointer to member function you need following syntax: 要获取指向成员函数的指针,您需要以下语法:
callFunc(&testClass::aFunc1);
But note, that to invoke member function you need have class instance. 但是请注意,要调用成员函数,您需要具有类实例。 So callFunc needs 2 parameters (I'm using template but you can change it to testClass):
所以callFunc需要2个参数(我正在使用模板,但是您可以将其更改为testClass):
template <class T>
void callFunc(T*inst, void (T::*member)())
{
(inst->*member)();
}
So correct call of callFunc looks like: 因此,正确调用callFunc如下所示:
void testClass::aFunc2()
{
callFunc(this, &testClass::aFunc1);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.