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

标签 c++ function-pointers

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

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

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

最佳答案

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

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

这里需要一组括号:

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

关于C++:通过指针调用成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16778498/

相关文章:

c - 函数指针模拟方法在 C 中有害吗?

c++ - 指向成员表示的指针

c++ - 如何在 C++ 程序中使用 C 头文件?

c++ - 数值转换

C++ "Choice" union

c++ - 函数名称上不明确的星号运算符

c++ - 使用模板函数指针声明模板函数

c++ - 错误 : request for member size in . .. 非类类型 char

c++ - C++ 中的原子性 : Myth or Reality

c++ - 如何使用 FreeImage 获取子图像