2012-10-09 36 views
1

首先,我想說這是一個硬件任務,我只是有關於誤差的問題,我現在面臨C++載體模板操作符[]

我做了一個插入功能,增加了一個DATA_TYPE矢量模板到動態數組的末尾。這是我目前的。

// Insert the value at the specified index by moving the tail 
// when Size = Capacity the Vector has to be reallocated first 
// to accomate the new element 
void Insert(const DATA_TYPE& value, int index){ 

    // If the Capacity is not large enough then ... 
    // allocate large vector 
    if (Size >= Capacity){ 
     // 0. Let's boost the capacity 
     Capacity += CAPACITY_BOOST; 
     // 1. Allocate new larger vector 
     DATA_TYPE* newData = new DATA_TYPE[Capacity]; 

     // 2. Copy from old Data into the newData 
     for(int i=0; i< Size; i++) 
       newData[i] = Data[i]; 

     // 3. Delete the old Data 
     delete[] Data; 

     // 4. Replace old Data-pointer with the newData pointer 
     Data = newData; 
    } 

    // Move the tail 
    for(int i=index; i<Size;i++){ 
     Data[i+1] = Data[i]; 
    } 

    // Insert 
    Data[index] = value; 
    Size++; 

} 
DATA_TYPE& operator[] (int index) const{ 
    return *this[index]; 
} 

注意:使用私有變量:尺寸,容量,數據(存儲動態數組) 我敢肯定,我已經正確地實現添加或功能的push_back。問題是,當我試圖像cout < < a [1];「我得到一個錯誤。

while compiling class template member function 'int &Vector<DATA_TYPE>::operator [](int) const' 
     with 
     [ 
      DATA_TYPE=int 
     ] 
see reference to class template instantiation 'Vector<DATA_TYPE>' being compiled 
    with 
    [ 
      DATA_TYPE=int 
     ] 
error C2440: 'return' : cannot convert from 'const Vector<DATA_TYPE>' to 'int &' 
    with 
    [ 
     DATA_TYPE=int 
     ] 
+0

請堅持每個帖子有1個問題。 –

+0

對不起,感謝您的支持 – wzsun

回答

5

應該有2個版本的operator[]的:

const DATA_TYPE& operator[] (int index) const; 
DATA_TYPE& operator[] (int index); 

你有什麼是兩者的組合怪異。

你也應該返回

return Data[index]; 

返回(*this)[index];會導致無限遞歸調用(當然,不是無限的,你會得到在此之前,一個計算器)。

+0

+1你能解釋無限遞歸部分嗎?我想我完全不瞭解它。 – Mahesh

+0

@Mahesh肯定 - '(* this)[index]'相當於直接調用'operator [](index)',它會一次又一次地調用它自己。 –

+0

哦,狗屎我拖了,我之前,但當我打電話給我的功能顯示通過cout我試圖顯示錯誤的索引(即[1]而不是[0]),並假定它必須改變*這[指數]。我覺得啞巴。不管怎麼說,多謝拉。 – wzsun

1

operator[]函數被聲明爲恆定的,即,它不能改變在Vector對象任何東西。但是它返回一個引用,這意味着返回值可以修改。這兩個相互矛盾。

這可以通過從函數結尾刪除const或者不返回引用來解決。

+0

這不是什麼OP代碼錯誤。這可能不是一個好習慣,但它不是一個實際的錯誤(至少在正確實現'operator []'的時候)。 – Grizzly

2

有三個問題在這裏:

  1. 運算符優先級。 *this[index]被解析爲*(this[index]),而你的意思是(*this)[index]
  2. 您正在從const方法返回對您的數據的可變引用。
  3. operator[]的定義是循環的。在operator[]中返回(*this)[index]會導致無限遞歸。
+0

從技術上說,從該運算符返回可變引用沒有任何問題(因爲引用是由數據本身不是const的對象中的指針指向的數據)。不管這是否是好的做法可能會有爭議,並取決於用例,但我不會說這是一個問題 – Grizzly

+0

@Grizzly:我不認爲這是老師的期望。 –

+0

我真的不想推測這一點(根據我的經驗,方法簽名經常在這類練習的作業中給出)。這就是爲什麼我會說這是一個有用的建議,而不是那麼少的讀者解釋它,因爲你不能這樣做。 – Grizzly