سؤال

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.

هل كانت مفيدة؟

المحلول

You are wrong assuming that in line

cout << "a =" << (*v)[0] << endl;

The

const value_type & Vector::operator[] ( long index ) const

will be used.

In fact both times

value_type & Vector::operator[]

is used so you "replace" previous value with new (and leaking memory at the same time)

below should help

value_type & Vector<value_type>::operator[] ( long index ) {
    if ( index < 0 || index > usedSize )
        ///out of bounds handling
    else {
        if(vector[index]== 0)
        {
            vector[index] = new value_type () ;
            usedSize++ ;
        }
        return *(vector[index]) ;
    }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top