subscript operator problem

Started by
3 comments, last by drkpriest 19 years, 7 months ago
Say if i had a pointer class which was a reference counter and a dynamic array class, how would i override the ctor in the array class to use the [] operators.


template<class T>
class Pointer
{
private:
    T* object;
public:
    operator T*()
    {
        return (object);
    }
    // other functions here, emitted for ease of reading
};

template<class T>
class Array
{
private:
    T* array;
    unsigned long arraySize;
public:
    Array(unsigned long size)
    {
        arraySize = size;
        array = new T[size];
    }
    T& operator [](size_t index)
    {
        return (array[index]);
    }
    operator T*()
    {
        return (array);
    }
    // other functions here, emitted for ease of reading
};

int main()
{
    Pointer<Array<int> > myarray;
    myarray = new Array<int>(5);
    
    myarray[4] = 6;

    return0;
}



Why is it that the array ctor gets called at the line myarray[4]=6; instead of the [] overload ?? and how can i access the [] overload method??
Advertisement
(*(myarray()))[4] = 6;
says there is:

no match for call to '(Pointer<Array<int> >)()'
sorry,

(*((Array*)myarray))[4] = 6;
i figured it out..

i just took out the pointer cast method and you can access it like this:

(*(myarray))[4] = 6;

this de-references the object pointer in Pointer and runs the de-reference overload method in Array which passes it to the subscript operator method. yippee.. however i think i might just incorporate the Pointer stuff into Array..

cheers for that man.

This topic is closed to new replies.

Advertisement