簡體   English   中英

如何為Template Class - C ++編寫復制構造函數

[英]How to write a copy constructor for Template Class - 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

如何正確聲明復制構造函數?

注:這是一個項目,我不能改變頭聲明,所以建議喜歡這個 ,雖然有用,但不是在這種特定情況下有幫助。

謝謝你的幫助!

注意:您聲明一個賦值運算符,而不是復制構造函數

  1. 你在返回類型之前錯過了const限定符
  2. 您錯過了返回類型和函數參數的模板參數( <T>

用這個:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM