[] operator

Hi.
I wrote a class like below:
1
2
3
4
5
6
7
8
class MyClass
{
   private:
      char Array[100];
      . . .
   public:
      . . .
};

How can I Access Array elements by using MyClass Object?
for example:
1
2
MyClass Obj;
cout << Obj[2]; // <-- I want This Line Prints Array[2] in Obj instance 

Thanks :-)
Either make the array public (may be not what you want) or implement operator[]:

1
2
3
4
5
6
7
8
9
10
class MyClass {
    char Array[ 100 ];

  public:
    char& operator[]( size_t index ) 
        { return Array[ index ]; }

    char operator[]( size_t index ) const
        { return Array[ index ]; }
};
How Can I overload [] operator when Array is 2D?
There are ways, but generally you shouldn't.

Use the () operator instead.

See the "Array2D" example I made here:

http://www.cplusplus.com/forum/articles/17108/#msg85595
Here is how you overload [] operator for 2D arrays:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
using namespace std;

class column
{
	static const size_t MAX_COLS = 2;
	char cols[MAX_COLS];
public:
	char& operator[](size_t index){
		return cols[index];
	}
};

class array2d
{
	static const size_t MAX_ROWS = 10;
	column rows[MAX_ROWS];
public:
	column& operator[](size_t index){
		return rows[index];
	}
};

int main()
{
	array2d test;
	test[5][0] = 'Y';
	cout << test[5][0] << endl;
}
@naivnomore: You'll regret posting this...
Well it's like I said. There are ways, but you generally shouldn't.

Reasons not to do it the way naivnomore suggested:


- exposing the user to internal types just adds to type confusion, ultimately making the class more error prone and harder to use.

- it makes const correctness more difficult

- it takes more code to write

- it makes built in bounds checking more difficult

- it makes an assumption about how the class has to store the array internally. For example in his situation, his class must have 'column's instead of having the actual data directly. This makes it impossible to have a dynamic array that's stored linearly with this approach. (read: stored linearly = less memory, faster access)

- etc

- etc
Topic archived. No new replies allowed.