【发布时间】:2012-11-05 16:36:22
【问题描述】:
我正在尝试了解有关模板的更多信息,但遇到了一个我似乎无法解决的问题。目前,下面的课程工作正常。
#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;
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。有谁知道标准向量类如何实现这一点?任何帮助都会很棒。谢谢!
【问题讨论】:
-
你的赋值运算符没有清除旧数据。
标签: c++ templates constructor