2016-11-30 35 views
-2

我寫了一個簡單的類,它使用接收索引和兩個要計算的值的方法執行基本的算術運算。函數指針的數組C++

索引指示在包含指向函數的表的表中執行哪個操作。

這裏是我的代碼:

#include <iostream> 

using namespace std; 

class TArith 
{ 
public: 

    static const int DIV_FACTOR = 1000; 

    typedef int (TArith::*TArithActionFunc)(int,int); 

    struct TAction 
    { 
     enum Values 
     { 
      Add, 
      Sub, 
      Mul, 
      Div, 
      count, 
     }; 
    }; 

    int action(TAction::Values a_actionIdx, int a_A, int a_B) 
    { 
     return (this->*m_actionFcns[a_actionIdx])(a_A,a_B); 
    } 

private: 
    int add(int a_A, int a_B) 
    { 
     return a_A + a_B ; 
    } 

    int sub(int a_A, int a_B) 
    { 
     return a_A - a_B ; 
    } 

    int mul(int a_A, int a_B) 
    { 
     return a_A * a_B ; 
    } 

    int div(int a_A, int a_B) 
    { 
     return (0 != a_B) ? (DIV_FACTOR*a_A)/a_B : 0; 
    } 

    static TArithActionFunc m_actionFcns[TAction::count]; 
    int m_a; 
    int m_b; 
}; 

TArith:: TArithActionFunc TArith:: m_actionFcns[TAction::count] = { 
    TArith::add, 
    TArith::sub, 
    TArith::mul, 
    TArith::div 
}; 

void main(void) 
{ 
    TArith arithObj; 
    int a=100; 
    int b=50; 

    for(int i = 0 ; i <TArith::TAction::count ; ++i) 
    { 
     int k = (i == (int)TArith::TAction::Div) ? TArith::DIV_FACTOR : 1;  
     cout<<arithObj.action((TArith::TAction::Values)i,a,b)/k<<endl; 
    } 
    cout<<endl; 
} 

編譯器說:

'TArith::add': function call missing argument list; use '&TArith::add' to create a pointer to member 
'TArith::sub': function call missing argument list; use '&TArith::sub' to create a pointer to member 
'TArith::mul': function call missing argument list; use '&TArith::mul' to create a pointer to member 
'TArith::div': function call missing argument list; use '&TArith::div' to create a pointer to member  
+8

你嘗試做什麼,編譯器提示? – NathanOliver

+3

嚴重的是,編譯器在錯誤信息中給出了答案。* – Angew

回答

2
TArith:: TArithActionFunc TArith:: m_actionFcns[TAction::count] = { 
    TArith::add, 
    TArith::sub, 
    TArith::mul, 
    TArith::div 
}; 

的指針一類C&C::f的成員函數f正確的語法。您錯過了領先的&

嘗試:

TArith:: TArithActionFunc TArith:: m_actionFcns[TAction::count] = { 
    &TArith::add, 
    &TArith::sub, 
    &TArith::mul, 
    &TArith::div 
}; 
+0

謝謝, 工作就像一個魅力 –