Assigning C++ function pointers to member functions of the same object

廉价感情. 提交于 2019-12-12 11:05:58

问题


How do I get the function pointer assignments (and maybe the rest) in test.calculate to work?

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

回答1:


There are several problems with your code.

First, int (*opPtr)() = NULL; isn't a pointer to a member function, its a pointer to a free function. Declare a member function pointer like this:

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

Second, you need to specify class scope when taking the address of a member function, like this:

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

Finally, to call through a member function pointer, there is special syntax:

return (this->*opPtr)();

Here is a complete working example:

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



回答2:


Like this int (test::*opPtr)() = NULL;. Refer http://www.parashift.com/c++-faq-lite/pointers-to-members.html#faq-33.1

Edit: Also use if (operatr == '+') opPtr = &test::add; instead of [..] = this.add and return (this->(opPtr))(); instead of return opPtr();. In fact, use typedefs and macros like the FAQ says and probably member function paramaters instead of class members a and b.



来源:https://stackoverflow.com/questions/4864341/assigning-c-function-pointers-to-member-functions-of-the-same-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!