【问题标题】:Get pointer to member function from within member function in C++从 C++ 的成员函数中获取指向成员函数的指针
【发布时间】:2010-12-26 07:49:06
【问题描述】:

目前在我尝试编写的程序中,我需要能够获得指向同一类的成员函数中的成员函数的指针。指针需要作为 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() )

【问题讨论】:

    标签: c++


    【解决方案1】:

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

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

    【讨论】:

    • 问题是,理论上的 callFunc 函数不能被修改,因为它是来自 GLUT 的 glutDisplayFunc 函数,它需要一个 void(*)()。还是谢谢。
    【解决方案2】:

    这篇文章我看了一遍,觉得很有意思:

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

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

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

    【讨论】:

    • 谢谢,但是在这两篇文章中(我在发布这篇文章之前已经阅读过),据我所见,它假设你已经在某个地方初始化了类。对于我要实现的实现,需要指针的函数是类本身的一部分,因此我不能像这样访问类:“functionRequiringPointer(initializedClass.someFunc);”。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-02
    • 2022-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多