【发布时间】:2012-07-06 08:18:35
【问题描述】:
下面是Vector的一个模板类,它存储了不同类型的数据元素。检查复制构造函数的代码和主代码。我所期望的语句“cout
有人可以帮我吗?谢谢。
template<typename T>
class Vector{
private:
T* ptr;
int size;
public:
Vector<T>(int s = 10){
size = s;
if(size!=0)
{
ptr = new T[size];
}else{
ptr = 0;
}
}
Vector<T>(const Vector<T> ©){
this->size=copy.getSize();
if(size !=0)
{
ptr=new T[size];
for(int i=0;i<size;i++)
ptr[i] = copy.ptr[i];
}else{
this->ptr=0;
}
}
~Vector<T>(){
if(size>0)
{
delete[] ptr;
}
}
int getSize() const
{
return size;
}
const Vector<T> & operator = (const Vector<T> &rhs){
if(this!=&rhs)
delete [] this->ptr;
size = rhs.size;
if(size!=0)
{
ptr=new T[size];
for(int i=0;i<size;i++)
ptr[i] = rhs.ptr[i];
}
return *this;
}
T& operator[](int index){
if(index>=0 && index<=size)
return ptr[index];
}
};
int main(int argc, char *argv[])
{
Vector<char*> vCHAR(10);
vCHAR[0]="asset";
vCHAR[1]="income";
vCHAR[2]="liability";
Vector<char*> vCHAR2(vCHAR);
vCHAR[2] = "expense";
cout << vCHAR[2] << endl;
cout << vCHAR2[2] << endl;
system("PAUSE");
return EXIT_SUCCESS;
}
【问题讨论】:
-
请注意,您将字符串文字(例如
"asset")分配给char*。那是自找麻烦。将char*设为const。 -
我强烈建议您使用
std::string而不是字符指针。
标签: c++ class templates constructor