开发者

Simple user defined vector template example

Consider the following code:

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;开发者_Python百科 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;

}

If I call second conversion ctor

      v1=vecTor<int>(a,3);

I get a segmentation fault at codepad.org; it crashes on mingw. What could be the problem?


You aren't initializing T*

vecTor(T *x,int s) : size(s), v(new T[size]) 
{
    for(int i=0; i<size; i++)
    v[i] = x[i];
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜