#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
template <typename T>
class Array
{
private:
T* e1_;
size_t len_;
size_t siz_;
public:
Array():e1_(NULL),len_(0),siz_(0){}
Array(size_t n):len_(n),siz_(2*n),e1_(NULL)
{
e1_=new T[siz_];
}
T& operator[](int i)
{
return e1_[i];//之后a[i]=a.e1_[i];
}
~Array(){delete []e1_;}
};
int main()
{
Array<string> a(10);//a对象 a.e1_[10];
// for(int i=0;i<10;i++)a[i]=i*1.0;//相当于a.e1_[i]=i;
// for(int i=0;i<10;i++)cout<<fixed<<setprecision(2)<<a[i]<<" ";
a[0]="abc";//a.e1_[0]
a[1]="abcd";
a[2]="xy";
a[3]="xyz";
for(int i=0;i<4;i++)
cout<<a[i]<<" ";
return 0;
}
1、在main函数中使用类模板的时候不要忘记在类名后面写<类型>;
2、注意[]的重载;