简体   繁体   中英

How to write a copy constructor for Template Class - C++

In my header file I have

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

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

and here is one declaration which I've tried so far

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;
}

this is what the compiler is telling me

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

How do I properly declare the copy constructor?

Note: This is for a project and I cannot change the header declaration, so suggestions like this , while useful, are not helpful in this particular instance.

Thanks for any help!

NOTE: You declare an assignment operator, not copy constructor

  1. You missed the const qualifier before return type
  2. You missed the template argument( <T> ) for return type and function argument

Use this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM