operator []

HI EXPERTS,
Question about overloading operator[]..
im wondering how im going to create a 2D object like 2D array....
in my main i want smth like this MyObj obj[5][5]
i just have no idea how to do it...so i just try a code below and heven't tested yet =DDD

code:
1
2
3
4
MyObj operator[](int a){   //i jus make the return value to the object itself?
 this->data = new int*[a];
 return *this;
}



thx for reading...
You don't.

You use the () operator instead:

1
2
//foo[1][2];  // bad
foo(1,2);  // good 



http://cplusplus.com/forum/articles/17108/#msg85595 <-- see the example "Array2D" class near the end of this post
nice article..but maybe is my mistake that i didt mention that i just want to know the structure how actually the program read smth like x[1][1] or x(1)(1) i just wan to know the structure not how to use or do it...=)
Because i just learned operator () so in my program i just can do x(1) simple 1 but how if i wan try x(1)(1) ? Just curious about it....
but x(1)(1) is unintuitive and makes no sense. Just do x(1,1).

What you're asking is technically possible, but is very bad practice. It could be accomplished by making the first [] operator return an intermediate type (like a new class). The intermediate type would then also overload the [] operator to return the actual element you want to index.

But that potentially incurs some overhead, slowing your program down, and makes your code atrociously messy. So don't bother.
Last edited on
Topic archived. No new replies allowed.