I'm implementing a vector, so i wanted it to behave as an array. That's the reason i tried to implement the subscripting operator but i haven't achieve the correct behavior.
The implementation was something like this:
template <typename value_type>
class Vector{
private:
value_type ** vector ;
long size ;
long usedSize ;
public:
/.../
value_type & operator [] (long) ; // For writing.
const value_type & operator [] (long) const ; // For reading.
/.../
}
template<typename value_type>
value_type & Vector<value_type>::operator[] ( long index ) {
if ( index < 0 || index > usedSize )
return out_of_range () ;
else {
vector[index] = new value_type () ;
usedSize++ ;
return *(vector[index]) ;
}
}
template<typename value_type>
const value_type & Vector<value_type>::operator[] ( long index ) const {
if ( index < 0 || index > usedSize )
return out_of_range () ;
else { return (*vector[index]) ; }
}
Then i test the behaviour of the object with this:
int main (void) {
Vector<int> * v = new Vector ( 10 ) ; // Creates a vector of 10 elements.
(*v)[0] = 3 ;
int a = (*v)[0] ;
cout << "a = " << a << endl ;
}
And i get this from the execution:
$> a = 0
Some threads recommend using a handler class overloading the assignment operator, i wonder if there's anyway to avoid the use of a handler object to do the task.
Thanks in advance.
Gonzalo from Argentina.
usedSizeis initialized to 0 then wouldn't any call tooperator[]returnout_of_range()instead of a place in your array? What doesout_of_range()look like?cout << "a = " << 0-- did you meancout << "a = " << a?index = 0the conditional statement its false, because index is equal to usedSize not greater. out_of_range its a standard c++ exception. See it here