假設包含正確的標頭。在構造函數中初始化數組或向量
我有一個計算器的各種功能類。我針對不同的運營商類型(空值,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
}
瑣碎與C++初始化列表...否則只是在構造函數中使用'push_back'。 – nneonneo
對於C++ 11而言,'vector'很容易。這比之前的情況要困難得多。 –