问题描述:

I'm writing a collection class. I want to overload the square brackets operator ([]) to provide access to elements in the collection.

int operator[](int i)

{

// Do stuff here

}

My problem is that I don't see how to write this so that I could use this operator to accept a value:

myClassInstance[0] = value;

I see no way to declare the square brackets operator with an additional argument (the value to assign to the element).

I know I can simply return int& and the caller can assign a value to that, but internally each element is stored in a different format than the one made public.

Is this even possible?

网友答案:

Write an int_proxy class that is implicitly convertible to int and is assignable from int. You'll need at least two member functions:

operator int();
int_proxy& operator=(int);

In this proxy class, store whatever information you need to be able to retrieve and set the value in the container. Do the retrieval in the conversion operator and the assignment in the assignment operator.

网友答案:

Return a reference to an object that has an operator = that can stuff the int where it needs to go. Look at the boolean vector trickery in STL for an example, if not necessarily a wonderfully exemplary example.

网友答案:

write:

    int& operator[](int i)
    {
        // Do stuff here
    }
相关阅读:
Top