如何为Template Class - C ++编写复制构造函数

时间:2013-02-12 01:29:50

标签: c++ templates copy-constructor

在我的头文件中,我有

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这样的建议虽然有用,但在这个特定实例中没有帮助。

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

注意:您声明了赋值运算符,而不是复制构造函数

  1. 您在返回类型
  2. 之前错过了const限定符
  3. 您错过了返回类型和函数参数
  4. 的模板参数(<T>

    使用此:

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