Hi Everybody,
I'm writing a String class for a school assignment.
The String class is supposed to include a char* pCh pointer to a character array to store the actual string, this is OK.
Then the teacher asked us to include an operator overloading for char* so that every time the compiler can treat a String object as a character pointer it would get access to the char* pCh pointer in the object... other than feeling this breaks encapsulation, I believe it's OK... after all he is the teacher.
This is my implementation of that:
The problem arises when the teacher asks us to include another operator overload, this time for the [] operator... as to provide direct access to each of the strings characters... again... encapsulation issues, but that's not the problem...Code:String :: operator char*() const { return pCh; }
This is my implementation if THAT:
Everything seems fine so far?Code:char& String :: operator[](unsigned int i) const { if(i >= length) abort(); return pCh[i]; }
The problem is that when trying to actually test my program, the compiler doesn't know what to do... should it first use the operator char* overload on the String and then treat the following [i] the same way any pointer can be accessed (e.g. int* p; int a = p[3]; ) or use my operator[](usigned int i) and correctly return a reference to a character???
How do I tell the compiler that I mean the operator[]? Is there a way to set a presedence order telling the compiler that in the case that a string object is followed by [i] use the correct operator overloading function?Code:String a("Ambiguity!"); char m = a[1]; /* supposed to make char m contain the actual 'm' character in position 1 in string a */



LinkBack URL
About LinkBacks


