小编too*_*hin的帖子

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

如何让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)

c++ member-function-pointers this-pointer

5
推荐指数
1
解决办法
8177
查看次数