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". with
MyClass oskar;
it works, though. how can i use the overloaded [] for pointers? i also need
to overload arithmetic operations in my class, is there a similar problem
when dealing with referenced objects?
thanks in advance and greetings, jonas
You cannot overload operator[] for pointers, you cannot overload any
pointer operator.
It sounds like you want a class that overload several operators but
behaves like a pointer otherwise. Well, that is what you must write
class MyPtrClass
{
public:
int operator[](int i);
// etc...
private:
MyClass* ptr;
};
In other words write a class that contains a single pointer to another
class, and put the overloaded operators there.
john