将C++函数指针分配给同一对象的成员函数

too*_*hin 5 c++ member-function-pointers this-pointer

如何让test.calculate中的函数指针赋值(可能还有其余的)工作?

#include <iostream>

class test {

    int a;
    int b;

    int add (){
        return a + b;
    }

    int multiply (){
        return a*b;
    }

    public:
    int calculate (char operatr, int operand1, int operand2){
        int (*opPtr)() = NULL;

        a = operand1;
        b = operand2;

        if (operatr == '+')
            opPtr = this.*add;
        if (operatr == '*')
            opPtr = this.*multiply;

        return opPtr();
    }
};

int main(){
    test t;
    std::cout << t.calculate ('+', 2, 3);
}
Run Code Online (Sandbox Code Playgroud)

Joh*_*ing 10

您的代码有几个问题.

首先,int (*opPtr)() = NULL;它不是指向成员函数的指针,它是指向自由函数的指针.声明一个成员函数指针,如下所示:

int (test::*opPtr)() = NULL;

其次,在获取成员函数的地址时需要指定类范围,如下所示:

if (operatr == '+') opPtr = &test::add;
if (operatr == '*') opPtr = &test::multiply;
Run Code Online (Sandbox Code Playgroud)

最后,要通过成员函数指针调用,有一些特殊的语法:

return (this->*opPtr)();
Run Code Online (Sandbox Code Playgroud)

这是一个完整的工作示例:

#include <iostream>

class test {

    int a;
    int b;

    int add (){
        return a + b;
    }

    int multiply (){
        return a*b;
    }

    public:
    int calculate (char operatr, int operand1, int operand2){
        int (test::*opPtr)() = NULL;

        a = operand1;
        b = operand2;

        if (operatr == '+') opPtr = &test::add;
        if (operatr == '*') opPtr = &test::multiply;

        return (this->*opPtr)();
    }
};

int main(){
    test t;
    std::cout << t.calculate ('+', 2, 3);
}
Run Code Online (Sandbox Code Playgroud)