我是 C++ 的新手,听说过如此强大的技术 - 模板。
这是我的类中的构造函数
node(const double f) {
this->type = FLOAT;
this->data.f = f;
}
node(const int i) {
this->type = INTEGER;
this->data.i = i;
}
//construct a vector
node(const vector<int> arr) {
this->type = LIST;
for (int i=0; i<arr.size(); ++i) {
this->data.args.push_back(new node(arr[i]));
}
}
node(const vector<double> arr) {
this->type = LIST;
for (int i=0; i<arr.size(); ++i) {
this->data.args.push_back(new node(arr[i]));
}
}
它帮助我做这种事情
node* obj_i = new node({{1, 0},{0, -1}});
node* obj_f = new node({{1.0, 0.0},{0.0, -1.0}});
我确实必须为整数和浮点类型的数组写下初始化程序两次。有没有办法使用模板来完成它并用一个替换最后两个函数?
谢谢
UPD 我更深入并声明了矩阵的构造函数并得到了错误
//construct a matrix
node(const vector<vector<int>> arr) {
this->type = LIST;
for (int i=0; i<arr.size(); ++i) {
this->data.args.push_back(new node(arr[i]));
}
}
node(const vector<vector<double>> arr) {
this->type = LIST;
for (int i=0; i<arr.size(); ++i) {
this->data.args.push_back(new node(arr[i]));
}
}
error: call of overloaded 'node(<brace-enclosed initializer list>)' is ambiguous
node* matrix2 = new node({{0.0,7.7}, {3.3,-9.2}});
我似乎是我的技术根本上错了......