Re: Overload Operators for referenced objects?
Jonas Huckestein wrote:
hello,
somehow i can't figure out, how to overload the [] operator for a
referenced object. if i have
class MyClass {
int operator[](int i) { return 1; };
};
...
MyClass* oskar = new MyClass();
cout << oskar[3];
delete oskar;
the compiler says "cannot convert ???OperatorSequence??? to ???int??? in
initialization".
The compiler probably wants to say that it can't find an operator << that
takes a MyClass object. oskar[3] ist the same as *(oskar+3), expecting that
oskar is the pointer to the start of an array of MyClass, and you wan the
3rd element of that array.
with
MyClass oskar;
it works, though. how can i use the overloaded [] for pointers?
You are using it, but I guess you actually don't want to. If you want to use
the [] operator of your class instead of the one for pointers, you have to
dereference first:
cout << (*oskar)[3];
i also need to overload arithmetic operations in my class, is there a
similar problem when dealing with referenced objects?
Well, if you use a pointer, the operators for pointers will be used.