operator overloading

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • stephen henry

    #1

    operator overloading

    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
  • Victor Bazarov

    #2
    Re: operator overloading

    stephen henry wrote:[color=blue]
    > 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.[/color]

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

    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

    Comment

    Working...