2012-11-27 30 views
-1

我們剛剛在我的comp sci類中引入了泛型和模板。 我被要求創建一個支持任何數據類型的存儲和檢索的通用容器類。 我有我的所有功能工作正常,除非調整我的數組。我在我的插入函數中調用了大小調整:C++使用泛型/模板調整數組大小

template< typename T > 
void Container<T>::insert(T magic) 
{ 
    if (index == size) 
    { 
     resize(); 
    } 
    containerPtr[index] = magic; 
    index++; 
} 

大小變量是數組大小,索引是下一個插入位置。

,這裏是我的調整大小功能:

template< typename T > 
void Container<T>::resize() 
{ 
    int doubSize = size * 2; 
    Container<T> temp(doubSize); 
    for (int i = 0; i < size; i++) 
    { 
     temp[i] = containerPtr[i];  // error 1 here 
    } 
    *containerPtr = temp;    // error 2 here 
    size = doubSize; 
} 

我重載=

template< typename T > 
const T Container<T>::operator=(const T& rhs) 
{ 
    if(this == &rhs) 
    { 
     return *this; 
    } 
    return *rhs; 
} 

我收到以下錯誤,當我嘗試編譯:

1: error C2676: binary '[': 'Container<T>' does not define this operator or a conversion to a type acceptable to the predefined operator 
2: error C2679: binary '=': no operator found which takes a right-hand operand of type 'Container<T>' (or there is no acceptable conversion) 

我不知道我在這裏錯了...

+0

首先=是assigment運算符,你不分配任何東西。 2.在退貨聲明中解除這一點。 3.重新分配存儲.... 4.刪除第二個for循環等 – neagoegab

+0

'containerPtr'是什麼? – ecatmur

+0

http://courses.cms.caltech.edu/cs11/material/cpp/donnie/cpp-ops.html – neagoegab

回答

1

2:錯誤C2679:二進制「=」:沒有操作員發現這需要類型的右邊的操作數「容器」(或沒有可接受的轉化率)

是更重要的錯誤,它表明,你相信什麼樣的類型是在

* containerPtr = temp;

這行代碼不正確。要將container<T>分配給您正在嘗試執行的T值是不可能的。在將temp更改爲指向具有正確大小的T的動態分配數組的指針(並刪除指定的指針deref)後,另一個錯誤將自行消失。請注意,您還需要修復內存泄漏,因爲您忘記刪除之前的陣列。

+0

我認爲這是問題所在。我已更正,現在可以正常工作。我仍然必須修復內存泄漏,然後應該是好的。謝謝您的幫助! –

0

錯誤1: 敢肯定,你必須定義operator[]爲您的Container類

錯誤2: 超載operator=時,應使用以下簽名:

template< typename T > 
const T Container<T>::operator=(const Container<T>& rhs) 
{ 
    ... 
} 
3

此錯誤

temp[i] = containerPtr[i];  // error 1 here 

很可能是因爲您尚未定義operator[](size_t)以允許您使用方括號訪問容器元素。你需要像這些const和non-const的運營商:

T& operator[](std::size_t index) { return containerPtr[index]; } 
const T& operator[](std::size_t index) const { return containerPtr[index]; } 

假設containerPtr某種動態大小的數組持有T對象。並且這一行:

*containerPtr = temp;    // error 2 here 

是錯誤的。 *containerPtr的類型爲T,並且您試圖將Container<T>分配給T。這是不太可能的。

我建議你用std::copy而不是循環和賦值,雖然我意識到這可能違揹你的任務的精神。

+0

感謝您的信息。我認爲我的錯誤2是問題真正奠定的地方。我解決了這個問題,現在它可以正常工作。因爲他的回答是第一次,所以我把支票給了stonemetal。 –