【问题标题】:One class method call another one via function pointer一个类方法通过函数指针调用另一个类方法
【发布时间】:2014-01-02 06:04:29
【问题描述】:

由于某种原因,我必须通过函数指针从同一类的另一个方法调用类方法。 这是说明我的问题的示例代码:

class testClass 
{
....
private:
void method(int parameter) {
    .....
};
void callingMethod();
};
typedef  void (testClass::*classMethod)(int parameter);

void testClass::callingMethod() {
    classMethod method = &testClass::method;
    method(1);
}

我得到编译错误

错误 C2064:术语不计算为采用 1 个参数的函数。

进行此类调用的正确方法是什么?

【问题讨论】:

标签: c++


【解决方案1】:

你的语法是正确的,除了

method(1);

你应该使用

(this->*method)(1);

(*this.*method)(1);

【讨论】:

  • 谢谢。我的真实案例有一个方法指针表,做成员方法指针,它从表中获取值来完成这项工作。
【解决方案2】:

检查一下:

class testClass 
{
     public:
     int method(int parameter) 
     {
        cout << "Hi";
        return 0;
     };

     void callingMethod();
};


int (testClass::*pt2Member)(int) = NULL;

void testClass::callingMethod()
{
     pt2Member = &testClass::method;
     (*this.*pt2Member)(12);
     //classMethod method = &testClass::method;
     //*method(1);
}

int main()
{
    testClass objTest;
    objTest.callingMethod();
    return 0;
}

【讨论】:

    【解决方案3】:

    应该很简单

    (this->*method)(10);
    

    【讨论】:

    • 他们想通过成员指针而不是直接调用它,所以这个答案是错误的
    猜你喜欢
    • 2014-03-02
    • 2014-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-05
    • 1970-01-01
    • 2014-02-07
    • 1970-01-01
    相关资源
    最近更新 更多