2012-10-11 124 views
3

假設包含正確的標頭。在構造函數中初始化數組或向量

我有一個計算器的各種功能類。我針對不同的運營商類型(空值,Unirary,二進制,三元)有幾個結構。我想初始化一個向量(或者最好是一個數組),其中的元素填充爲我的計算器支持的元素。例如nul[]={{pi, "pi"}, {ans, "ans"}};我的程序會從輸入中取一個標記並搜索適當的操作符,返回該操作符的索引,然後調用正確的函數指針。我的問題是在構造函數中初始化一個數組或向量。如果有人能夠向我展示兩種方式,我會很感激。謝謝。以下是我的課程和未完成的構造函數。另外,如果你能想出一個更好的方式來寫我的計算器,我很樂意聽到它。

//operator class 
class Functions{ 
    public: 
     Functions(); 
     double pi(double x=0); 
     double answer(double& x); 
     double abs(double& x); 
     double pow(double& x); 
     double add(double& x, double &y) const; 
     double subtract(double& x, double& y) const; 
     double multiply(double& x, double& y)const; 
     double divide(double& x, double& y) const; 
     double max(double& x, double& y, double& z) const; 
     double volume(double& x, double& y, double& z) const; 
     void doc(); 
     bool weird(double &x) const; 
     unsigned findop0(const string & name); 
     unsigned findop1(const string & name); 
     unsigned findop2(const string & name); 
     unsigned findop3(const string & name); 
    private: 
     struct Nul{ 
      double (*nulf)(double & x); 
      string name; 
     }; 
     struct Uni{ 
      bool (*unif)(double & result, double x); 
      string name; 
     }; 
     struct Bin{ 
      bool (*binf)(double & result, double x, double y); 
      string name; 
     }; 
     struct Tern{ 
      bool (*terf)(double & result, double x, double y, double z); 
      string name; 
     }; 
     static const unsigned NUL_ELEMENTS = 2; 
     static const unsigned UNI_ELEMENTS = 2; 
     static const unsigned BIN_ELEMENTS = 4; 
     static const unsigned TRI_ELEMENTS = 2; 
     vector<Nul> nul; 
     vector<Uni> uni; 
     vector<Bin> bin; 
     vector<Tern> tri; 
}; 

Functions::Functions(){ 
    nul 
} 
+3

瑣碎與C++初始化列表...否則只是在構造函數中使用'push_back'。 – nneonneo

+0

對於C++ 11而言,'vector'很容易。這比之前的情況要困難得多。 –

回答

3

在C++ 11中,您可以在初始化列表中的一行中執行此操作。

struct C { 
    int a[20]; 
    int* b; 
    std::vector<int> c; 
    std::array<int,20> d; 
    C() : 
    a({1,2,3}), 
    b(new int[20]{1,2,3}), 
    c({1,2,3}), 
    d(std::array<int, 20u>{1,2,3}) 
    {} 
}; 

在C++中使用03多分配或使靜態函數來初始化向量或原始陣列。

struct C { 
    int a[20]; 
    int* b; 
    std::vector<int> c; 
    C() : 
    b(new int[20]), 
    { 
    a[0] = 1; ... 
    b[0] = 1; 
    c.push_back(1); 
    } 
}; 
+0

我討厭成爲一個麻煩,但它似乎仍然沒有工作。函數::函數(): nul({{pi,「pi」},{&answer,「ans」}}),uni({{&abs,「abs」},{&pow,「pow」}} , \t bin({{&add,「+」},{&subtract,「 - 」},{&multiply,「*」},{&divide,「/」}}), \t tri 「},{&卷,」 卷「}}) {}' 我不斷收到錯誤告訴我 '錯誤錯誤C2143:語法錯誤:缺少 ';'之前'}'' – Painguy

+0

哪個編譯器?它支持std :: vector的大括號初始化嗎? – PiotrNycz

+0

另一個問題 - 你的函數必須是靜態的以匹配你的結構函數類型。 – PiotrNycz