我想了解更多关于模板的知识,并遇到了一个我似乎无法解决的问题。目前下面的课程正常工作。初始化嵌套模板
#include <iostream>
#include <vector>
#include <cstring>
using namespace std;
template <class T, int s>
class myArray{
public:
T* data;
inline T& operator[](const int i){return data[i];}
myArray(){
data=new T[s];
}
myArray(const myArray& other){
data=new T[s];
copy(other.data,other.data+s,data);
}
myArray& operator=(const myArray& other){
data=new T[s];
copy(other.data,other.data+s,data);
return *this;
}
~myArray(){delete [] data;}
};
如果我使用它:
myArray<myArray<myArray<int,10>,20>,30> a;
现在是我可以与正常阵列括号例如访问30x20x10阵列一个[5] [5] [5]。我想添加一个功能,这样我可以这样写:
myArray<myArray<myArray<int,10>,20>,30> a(10);
并初始化所有条目,以10例。我无法解决如何做到这一点。据我所知,myArray的每一层都是使用默认构造函数构造的。如果我改变这对类似:
myArray(int n=0){
data=new T[s];
fill(data,data+s,n); //T might not be of type int so this could fail.
}
我认为,当数据不是int类型的(即在尺寸> 1的任何阵列上)这个失败,但是事实并非如此。它适用于数组为平方的情况,但如果不是,则某些条目不会设置为10.有人知道标准向量类如何实现此目的吗?任何帮助将是惊人的。谢谢!
你的赋值运算符不清理旧数据。 – Puppy