Self-similar vector template error []

I created my own vector template, operator[]

part of it:

template <class T>
T& vector<T>::operator[](unsigned int index)
{
    return m_Data[index];
}

      

I am using this code in the copy constructor of the class

Track::Track(const Track& src)
{
    for(unsigned int i = 0; i < src.sorted.size(); i++)
        AddCar(src.sorted[i]->rz, src.sorted[i]->owners.back()->name, src.sorted[i]->owners.back()->surname);
}

      

and I get the error 'no match for operator[] (operands types are const vector<Track*> and unsigned int)'

I tried to overload operator[]

using the keyword const

:

const T& operator[](unsigned int);

      

but this gave me another error: const T& operator[](unsigned int); cannot be overloaded

What could be the reason here?

+3


source to share


2 answers


You need to implement the const

version operator[]

like this:



template <class T>
const T& vector<T>::operator[](unsigned int index) const
{
    return m_Data[index];
}

      

+7


source


The reason is because you said there is no overloading const

, so you cannot apply []

to a vector const

.

You don't say what you tried or what happened, but this should work:



T const & operator[](unsigned int index) const {return m_Data[index];}    
T       & operator[](unsigned int index)       {return m_Data[index];}

      

+5


source







All Articles