How to overload [] operator to write for a class.
Oct 28, 2014 at 1:34pm UTC
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;
Oct 28, 2014 at 2:01pm UTC
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
Oct 28, 2014 at 2:46pm UTC
MiiNiPaa, how did you made your code runnable like that?
Oct 28, 2014 at 2:49pm UTC
Last edited on Oct 28, 2014 at 2:50pm UTC
Oct 28, 2014 at 3:00pm UTC
Interesting. Thanks
Topic archived. No new replies allowed.