C++ Vector Template operator []
-
06-07-2021 - |
Domanda
Firstly I wanted to say this is a HW assignment and I just have questions in regards to the errors I'm facing
I made a vector template with an insert function that adds a data_type to the end of a dynamic array. This is what I have currently.
// 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];
}
Note: Using Private Variables: Size, Capacity, Data(stores the dynamic array) I'm pretty sure I've implemented the add or push_back function correctly. The problem is when ever I try to cout something like "cout << a[1]; " I get an error.
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
]
Soluzione
There should be 2 versions of your operator[]
:
const DATA_TYPE& operator[] (int index) const;
DATA_TYPE& operator[] (int index);
What you have is a weird combination of the two.
You should also be returning
return Data[index];
Returning (*this)[index];
would result in an infinite recursive call (well, not infinite, you'll get a stackoverflow before that).
Altri suggerimenti
There are three problems here:
- Operator precedence.
*this[index]
is parsed as*(this[index])
, while you meant(*this)[index]
. - You're returning a mutable reference to your data from a
const
method. - The definition of
operator[]
is circular. Returning(*this)[index]
inoperator[]
would cause infinite recursion.
The operator[]
function is declared to be constant, i.e. it can't change anything in the Vector
object. But it returns a reference, which means that the returned value can be modified. These two contradicts each other.
This can be solved by either remove the const
from the end of the function, or to not return a reference.