C ++:通过指针调用成员函数

时间:2022-09-12 03:09:49

I have this example code of using pointer to member function, which I want to change during runtime, but I cannot make it work. I've already tried this->*_currentPtr(4,5) (*this)._currentPtr(4, 5). What is the proper way of calling pointer to method inside same class ?

我有这个使用指向成员函数的示例代码,我想在运行时更改它,但我不能使它工作。我已经尝试过这个 - > * _ currentPtr(4,5)(* this)._ currentPtr(4,5)。在同一个类中调用指向方法的正确方法是什么?

The error : expression must have (pointer-to-) function type

错误:表达式必须具有(指针指向)函数类型

#include <iostream>
#include <cstdlib>

class A {

public:

    void setPtr(int v);
    void useFoo();

private:
    typedef int (A::*fooPtr)(int a, int b);

    fooPtr _currentPtr;

    int foo1(int a, int b);
    int foo2(int a, int b);
};

void A::setPtr(int v){
    if(v == 1){
        _currentPtr = foo1;
    } else {
        _currentPtr = foo2;
    }
}

void A::useFoo(){

    //std::cout << this->*_currentPtr(4,5); // ERROR
}

int A::foo1(int a, int b){
    return a - b;
}

int A::foo2(int a, int b){
    return a + b;
}

int main(){

    A obj;

    obj.setPtr(1);
    obj.useFoo();

    return 0;
}

1 个解决方案

#1


23  

You need to tell the compiler which class the foos are coming from (otherwise it thinks they're functions from global scope):

你需要告诉编译器foos来自哪个类(否则它认为它们是来自全局范围的函数):

void A::setPtr(int v){
    if(v == 1){
        _currentPtr = &A::foo1;
                  //  ^^^^
    } else {
        _currentPtr = &A::foo2;
                  //  ^^^^
    }
}

and you need a set of parentheses here:

你需要一组括号:

std::cout << (this->*_currentPtr)(4,5);
          // ^                  ^

#1


23  

You need to tell the compiler which class the foos are coming from (otherwise it thinks they're functions from global scope):

你需要告诉编译器foos来自哪个类(否则它认为它们是来自全局范围的函数):

void A::setPtr(int v){
    if(v == 1){
        _currentPtr = &A::foo1;
                  //  ^^^^
    } else {
        _currentPtr = &A::foo2;
                  //  ^^^^
    }
}

and you need a set of parentheses here:

你需要一组括号:

std::cout << (this->*_currentPtr)(4,5);
          // ^                  ^