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);
}
4

2 回答 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);
}
于 2011-02-01T15:30:45.340 回答
3

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

编辑:也使用if (operatr == '+') opPtr = &test::add;代替代替. 实际上,使用常见问题解答中所说的 typedef 和宏,并且可能使用成员函数参数而不是类成员和.[..] = this.addreturn (this->(opPtr))();return opPtr();ab

于 2011-02-01T15:25:21.967 回答