char& myString::operator[] (constint index)
{
if (index < this->len || index> this->len) // this is saying that 'len' is the only possible index
return 255; // you cannot return a literal 255 as a non-const reference
returnthis->s[index];
}
The reason you can't return a literal is simple. What if someone tries to do this:
mystr[i] = 'v';
where 'i' is an out of range index. You'd effectively be trying to do 255 = 'v'; which is nonsense.
If you really want to do this, you'll need to have a dummy value:
1 2 3 4 5
char& myString::operator[] (constint index)
{
staticchar dummy;
if ( /*index is out of bounds*/ )
return dummy;
However note that you cannot really reliably specify what dummy is. You can initialize it with -1, but it can be changed at any time by the user doing this:
1 2 3
// assuming 'i' is out of bounds
mystr[i] = 'v'; // changes dummy to 'v'
cout << mystr[i]; // will print 'v', not -1 / 255
That's besides the point that char's range is only [-128..127], so it can't even represent 255 anyway.
Really the best way to handle an out of range error in this situation is to throw an exception.
Sure thing that exceptions are the way better than monkeying around with return values of different data types.
I just got a teacher who really waned us to return 255 as a char and then cast it as a int...