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

ash*_*hur 16 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;
}
Run Code Online (Sandbox Code Playgroud)

jro*_*rok 23

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

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

你需要一组圆括号:

std::cout << (this->*_currentPtr)(4,5);
          // ^                  ^
Run Code Online (Sandbox Code Playgroud)

  • @ashur这对于普通函数是正确的,但对于成员函数则不然.而后者不是常规指针. (2认同)
  • @ashur查看[本文](http://www.codeproject.com/Articles/7150/Member-Function-Pointers-and-the-Fastest-Possible),了解有关成员指针的详细信息. (2认同)