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

时间:2011-02-01 15:20:03

标签: 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);
}

2 个答案:

答案 0 :(得分: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 :(得分: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.add return (this-> (opPtr))();代替return opPtr();。事实上,使用类似于FAQ的typedef和宏,可能是成员函数参数,而不是类成员ab