首先,我想說這是一個硬件任務,我只是有關於誤差的問題,我現在面臨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
]
請堅持每個帖子有1個問題。 –
對不起,感謝您的支持 – wzsun