2013-02-12 156 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