繁体   English   中英

从C ++中的成员函数中获取指向成员函数的指针

[英]Get pointer to member function from within member function in C++

目前,我正在尝试编写程序,我需要能够获得指向同一类的成员函数中的成员函数的指针。 指针需要作为void(*)()传递给函数。 例:

//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;  
}

我正在尝试在GCC 4.0.1中执行此操作。 另外,被调用的成员函数不能是静态的,因为它引用了它所属的类中的非静态变量。 (如果您想知道,我需要在其中的特定实例是我需要能够将类的成员函数传递给GLUT函数glutDisplayFunc()的地方)

我阅读了这篇文章,发现它非常有趣:

http://www.codeproject.com/KB/cpp/FastDelegate.aspx

另外,有关成员函数指针的常见问题,请阅读以下内容:

http://www.parashift.com/c++-faq-lite/pointers-to-members.html

要获取指向成员函数的指针,您需要以下语法:

callFunc(&testClass::aFunc1); 

但是请注意,要调用成员函数,您需要具有类实例。 所以callFunc需要2个参数(我正在使用模板,但是您可以将其更改为testClass):

template <class T> 
void callFunc(T*inst, void (T::*member)())
{
    (inst->*member)();
}

因此,正确调用callFunc如下所示:

void testClass::aFunc2()
{
    callFunc(this, &testClass::aFunc1); 
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM