请考虑以下代码:
template<typename T>
class vecTor
{
int size;
T *v;
public:
vecTor(int s=0): size(s),
v(new T[size]) // conv. ctor [1]
{
for(int i=0; i<size; i++)
v[i]=0;
}
vecTor(T *x,int s) // [2] this conv. ctor produces seg. fault if called
{
size=s;
for(int i=0; i<size; i++)
v[i] = x[i];
}
void vecTorset(T *a,int s) // this method works fine
{ // instead of [2]
size=s;
for(int i=0; i<size; i++)
v[i] = a[i];
}
~vecTor()
{
delete [] v;
}
void printvec() const;
};
template<typename T>
void vecTor<T>::printvec() const
{
cout<<"Vector is:\n";
for(int i=0; i<size; i++)
cout<< v[i] <<" ";
cout<<"\n";
}
int main()
{
int a[3]= {3,5,7};
vecTor<int> v1(3);
v1=vecTor<int>(a,3); // this call produces seg. fault
//v1.vecTorset(a,3); //this call works fine
v1.printvec();
return 0;
}
如果我打电话给第二次转换ctor
v1=vecTor<int>(a,3);
我在codepad.org上遇到了分段错误;它在mingw上崩溃了。可能是什么问题?
答案 0 :(得分:6)
您尚未初始化T*
vecTor(T *x,int s) : size(s), v(new T[size])
{
for(int i=0; i<size; i++)
v[i] = x[i];
}