10-31-2004, 01:25 PM | #1 (permalink) |
Junkie
|
[C++] overloading [] on pointers
I have a vector and matrix class and i'm impementing an iterative method to solve a IBVP. In this class I have overloaded the [] to work on the class just fine.
However, now I have ran into a problem where I don't want to be passing around whole objects and copy them around I want to do it with pointers to the objects. However I still want to be able to use my array notation. So currently I use syntax like the following: Vector X(16); Vector *X0=&X; ... (*X0)[0]=..... I'd like to be able to just use X0[0]=.... So I tried adding a non-member function like the following double& operator[] (Vector* V, unsigned i) { return (*V)[i]; } however the compiler gives me an error saying [] must be a non static member. I can't see how to overload this operator as a static member. Anyone have any suggestions? |
11-01-2004, 10:35 PM | #3 (permalink) |
Junkie
|
Thanks that worked great. I never actually thought about creating refrences like that.
If I have X0 and X1 which are refrences to 2 different vectors swap(X0,X1) will only swap the refrence right? I want to make sure it behaves like a full deep copy without actually performing a deep copy. Also does anyone know if there is a way to overload [] operators not in a class? I think it would be really cool to make a class that behaved exactly like an array but with different symantics. Like array bounds checking, general bounds checking, maybe 1 based arrays instead of 2 based. It could be useful to develop using a class like this and then for a release move to the normal arrays. |
11-02-2004, 06:57 PM | #4 (permalink) |
Upright
|
You can only overload [] by member functions of a class. Same goes for = () ->
Not sure if this is what you mean WRT a class behaving like an array with different semantics...Use the STL containers. Use iterators to navigate over STL containers like the vector, and for element access use at(). You can try/catch an out of range error on the at() command as it does a range check. If you want you can still use the operator[], but you have to make sure you perform the range check. Iterators have the begin()/end() functions that should be used.
__________________
It's not that I don't care, it's just that I don't care enough! |
Tags |
overloading, pointers |
|
|