operator overloading

S

stephen henry

Hi All,

I have a class for which I have successfully overloaded the []
operator. I can now address the class (which is a 2d array) as
follows;

C2DArray array;

array[123][100] = 53;

Unfortunately, this does not work if array is a pointer, namely:

C2DArray *array = new C2DArray;

array[123][100] = 53; // Wrong!

I have to use:

(*array)[123][100] = 53;

instead.

Is there any way to overload the [] operator so that it work in the
case where array is the object and a pointer to the object. Either
that, or some nicer way of going about it...

Thanks,

Stephen
 
V

Victor Bazarov

stephen said:
I have a class for which I have successfully overloaded the []
operator. I can now address the class (which is a 2d array) as
follows;

C2DArray array;

array[123][100] = 53;

Unfortunately, this does not work if array is a pointer, namely:

C2DArray *array = new C2DArray;

array[123][100] = 53; // Wrong!

I have to use:

(*array)[123][100] = 53;

instead.

Is there any way to overload the [] operator so that it work in the
case where array is the object and a pointer to the object.

No, there is no way. Every pointer has [] defined for it, and you cannot
change that.
Either
that, or some nicer way of going about it...

What you _could_ do (although it's rather ugly) is

C2DArray &array = *(new C2DArray);
array[123][100] = 53;

of course you will need to dispose of it using the & syntax:

delete &array;

Victor
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,763
Messages
2,569,563
Members
45,039
Latest member
CasimiraVa

Latest Threads

Top