Quote:"const" because it prevents the following absurd use:(a = b) = c;
Why? If that's what they want to do, let them do it. Making the return value non-const doesn't cause any behavior that isn't fully expected and reasonable.
Quote:"const" because it prevents the following absurd use:(a = b) = c;
Quote:
(a = b) = c;
Quote:There should be two of them, and they will look like this:
Char& operator [](StringLength Pos);
const Char& operator [](StringLength Pos) const;
The first one allows you to write:
String x("abc");
c[1] = 'B';
and the second one allows you to do:
String x("abc");
Char c = x[1];
Without both, you can't do both of these things.
cannot convert 'this' pointer from 'const Code::String' to 'Code::String &'
const Char& String::operator [](StringLength Pos) const { if (Pos < 0) return Text[0]; else if (Pos >= Len) { Grow(Pos+2);//Error's here return Text[Pos]; } else return Text[Pos]; }
Quote:You're trying to modify the String object's state inside a function that is declared constant.const Char& String::operator [](StringLength Pos) const{ if (Pos < 0) return Text[0]; else if (Pos >= Len) { Grow(Pos+2);//Error's here return Text[Pos]; } else return Text[Pos];}
const Char& String::operator [](StringLength Pos) const{ if (Pos >= Len) { //Throw exception here return Text[0]; } else return Text[Pos];}
Quote:Original post by Chad Seibert
Nothing, as of now. StringLength is actually unsigned, so I don't know why I was checking to see if it was negative. I also got rid of grow() in the function.const Char& String::operator [](StringLength Pos) const{ if (Pos >= Len) { //Throw exception here return Text[0]; } else return Text[Pos];}
Thanks for all this great help!
Chad Seibert
Char String::operator [](StringLength Pos) const{ if (Pos >= Len) { throw std::out_of_range("String::operator[](StringLength) const: bounds error"); } else return Text[Pos];}
Quote:Original post by DeyjaOkay, in the second example I forgot to declare x as const. I did intend to.Quote:There should be two of them, and they will look like this:
Char& operator [](StringLength Pos);
const Char& operator [](StringLength Pos) const;
The first one allows you to write:
String x("abc");
c[1] = 'B';
and the second one allows you to do:
String x("abc");
Char c = x[1];
Without both, you can't do both of these things.
This is wrong. First, you can do both with the first non-const version. Second, the const version should not return a reference.