suppose I design a String class myself and I want to overload the operator functions, here are the choices:
String operator(const size_t index); String& operator(const size_t index); const String& operator(const size_t index) const;
any other combination of const, non-const and reference return type.
preguntado el 25 de agosto de 12 a las 12:08
 operador de un
string returns a character, not a string. Depending on circumstances, you should implement one or two of them:
const char& operator ( size_t index ) const; char& operator ( size_t index );
The first one produces a reference that cannot be modified. If your string is immutable, that is all you need.
The second one produces a reference that can be modified. You can use it to implement clever stuff, such as copy-on-modify and reference counting.
Some people prefer to have a signed parameter type for
operator, both to be more similar to built-in operator (they too support negative indices) and also to be able to detect negative value arguments (in case you have an out of bounds check).
The type that the C++ compiler uses to evaluate calling the built-in operator is
ptrdiff_t, so you will sometimes find the following
char &operator(ptrdiff_t index); char operator(ptrdiff_t index) const;
I usually just use a plain
int tipo de parámetro.