I know how to overload the array operator to GET a value:
a = myClass[1];
But how do i would i set the value like this:
myClass[1] = a;
I know how to overload the array operator to GET a value:
a = myClass[1];
But how do i would i set the value like this:
myClass[1] = a;
How does it make a difference ? You just have to make sure that myClass:perator [] returns a reference (which it should anyway).
Actually, there should be two versions of myClass::operator[]. One returns a reference, the other returns a const reference.
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
True. For const-correctness.
Edit: The one which returns a const reference should also be a const function.
Code:T_& myClass::operator [] (unsigned int i) { return mystuff[i]; } const T_& myClass::operator [] (unsigned int i) const { return mystuff[i]; }
Ok heres my new problem. I cant return a reference -_-.
Heres the code:
If i change it to:Code:T operator[](int pIndex) { if(pIndex >= 0 && pIndex < count) return items[pIndex]; return T(); }
error: invalid initialization of non-const reference of type 'int&' from a temporary of type 'int'Code:T& operator[](int pIndex) { if(pIndex >= 0 && pIndex < count) return items[pIndex]; return T(); //<<< this doesnt work }
Where T is int
Last edited by 39ster; 01-06-2008 at 05:57 PM.
Explain "doesn't work". It's Chinese to me.
You have a choice: you can simply return the index and make it the caller's responsibility to provide a valid index, or you can check and throw an exception (e.g., std::out_of_range) if the index is invalid. The former is what operator[] for the standard containers do, the latter is what the at() member function for the standard containers do.
You certainly cannot return a reference to a local temporary.
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
Right, because that way the compiler prevents you from doing this:
If you want to allow the above, then returning a temporary is not enough. You have to actually put the newly constructed object in your array.Code:Myclass[-1]=a;
Or you can decide on some other behavior for an invalid index as suggested by above.
It is too clear and so it is hard to see.
A dunce once searched for fire with a lighted lantern.
Had he known what fire was,
He could have cooked his rice much sooner.
Thanks. Also i just figured out what putting const at the end of const-safe functions does.
Code:const T& operator[](int pIndex) const { return items[pIndex]; } T& operator[](int pIndex) { return items[pIndex]; }
My homepage
Advice: Take only as directed - If symptoms persist, please see your debugger
Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"