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

5
我该如何让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);
}
2个回答

10

你的代码存在几个问题。

首先,int (*opPtr)() = NULL;不是成员函数指针,而是自由函数指针。声明成员函数指针应该像这样:

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

其次,在获取成员函数地址时需要指定类作用域,像这样:

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

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

return (this->*opPtr)();

这里提供一个完整的可工作示例:
#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);
}

1
@PeterMortensen:不要成为那种人。没有人喜欢那种人。 - John Dibling

3

像这样 int (test::*opPtr)() = NULL;。请参阅http://www.parashift.com/c++-faq-lite/pointers-to-members.html#faq-33.1

编辑:还要使用if (operatr == '+') opPtr = &test::add;,而不是[..] = this.addreturn (this->(opPtr))();,而不是return opPtr();。实际上,按照FAQ中的建议,使用typedef和宏,可能使用成员函数参数,而不是类成员ab


是的,但不仅仅是这一个问题。 - John Dibling

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接