operator overloading

Discussion in 'C++' started by stephen henry, Oct 26, 2004.

  1. 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
     
    stephen henry, Oct 26, 2004
    #1
    1. Advertising

  2. stephen henry wrote:
    > 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
     
    Victor Bazarov, Oct 26, 2004
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. John Smith
    Replies:
    2
    Views:
    434
    Ivan Vecerina
    Oct 6, 2004
  2. Replies:
    11
    Views:
    750
    James Kanze
    May 16, 2007
  3. hurcan solter
    Replies:
    3
    Views:
    741
    Cholo Lennon
    Aug 29, 2007
  4. Replies:
    11
    Views:
    570
  5. Replies:
    2
    Views:
    325
Loading...

Share This Page