2013-02-12 154 views
0

在我的头文件我有如何写一个拷贝构造函数模板类 - C++

template <typename T> 
class Vector { 
    public: 
     // constructor and other things 

     const Vector& operator=(const Vector &rhs); 
}; 

,这里是一个声明,我已经试过到目前为止

template <typename T> Vector& Vector<T>::operator=(const Vector &rhs) 
{ 
    if(this != &rhs) 
    { 
     delete [ ] array; 
     theSize = rhs.size(); 
     theCapacity = rhs.capacity(); 

     array = new T[ capacity() ]; 
     for(int i = 0; i < size(); i++){ 
      array[ i ] = rhs.array[ i ]; 
     } 
    } 
    return *this; 
} 

这是什么编译器告诉我

In file included from Vector.h:96, 
       from main.cpp:2: 
Vector.cpp:18: error: expected constructor, destructor, or type conversion before ‘&’ token 
make: *** [project1] Error 1 

如何正确地声明复制构造函数?

注意:这是针对一个项目,我不能更改标头声明,所以像this这样的建议虽然有用,但在这个特定的实例中没有帮助。

感谢您的帮助!

回答

2

注:声明赋值运算符,而不是拷贝构造函数

  1. 你错过了const预选赛返回类型前
  2. 你错过了返回类型和函数参数
  3. 模板参数( <T>

使用这个:

template <typename T> 
const Vector<T>& Vector<T>::operator=(const Vector<T>& rhs) 
+5

'''对于函数参数不是必需的,因为它在成员名称operator =后面,并且注入的类名称在范围内。同样,你也可以做'template auto Vector :: operator =(const Vector&rhs) - > Vector&' – aschepler 2013-02-12 02:37:33