2011-02-01 54 views
3

如何獲取test.calculate中的函數指針賦值(也許還有其他)?將C++函數指針分配給同一對象的成員函數

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

回答

8

您的代碼有幾個問題。

首先,int (*opPtr)() = NULL;不是指向成員函數的指針,它是指向自由函數的指針。聲明一個成員函數指針這樣的:

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

其次,你需要指定類範圍時採取成員函數的地址,如:

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

最後,調用通過成員函數指針,有特殊的語法:

return (this->*opPtr)(); 

這裏是一個compl ete工作示例:

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

謝謝,你剛剛救了我的一天。 – toochin 2011-02-01 15:43:04

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();。實際上,使用類似於常見問題解答的typedef和宏以及可能的成員函數參數而不是類成員ab

+0

是的,但還有更多的問題不止這個。 – 2011-02-01 15:31:07