How to overload [] operator to write for a class.

How would I overload this operator [] so that it will work for my class.
eg

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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
class String
{
public:
	//constructors.
	//default constructor.
	String();
	//constructor with parameters.
	String(const char*);
	//copy constructor.
	String(const String&);

	//assignment operator.
	String& operator = (const String&);

	//addition operator or concatenation.
	String& operator + (const String&);

	//+= operator.
	String& operator += (const String&);

	//subtraction operator.
	String& operator - (const String&);

	//-= operator.
	String& operator -= (const String&);

	//equality operator.
	bool operator == (const String&);

	//inequality operator: <=.
	bool operator <= (const String&);

	//index operator.
	char operator [](int);

	//reference operator.
	const char* operator &(const String&);

	//dereference operator ?

private:
	char *str;
	int size;
};


How can I achieve this for my assignment?
String abc[2];
abc[0] = something;
return reference to char instead of char itself:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
class foo
{
    int a[3];
public:
    int& operator[](int i)
    {
        return a[i];
    }
};

int main()
{
    foo x;
    x[1] = 42;
    std::cout << x[1];
}
42
MiiNiPaa, how did you made your code runnable like that?
? What you talking about?
If about little gear, it will appear nead every code in code tag which can compile.
If you mean output to the right, it is typed manually.
http://www.cplusplus.com/articles/z13hAqkS/
Last edited on
Interesting. Thanks
Topic archived. No new replies allowed.