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;およびの代わりにを使用します。実際、FAQにあるようなtypedefとマクロを使用し、おそらくクラスメンバーとの代わりにメンバー関数パラメーターを使用します。[..] = this.addreturn (this->(opPtr))();return opPtr();ab

于 2011-02-01T15:25:21.967 に答える