2016-11-30 17 views
-2

インデックスと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; 
} 

コンパイラは言う:C&C::fあるクラスのメンバ関数へのポインタfため

'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 
}; 

正しい構文

は、ここに私のコードです。先頭に&がありません。

試してみてください。

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

ありがとう、 は魅力的です –