"Kai-Uwe Bux" <jk********@gmx.netwrote in message
news:eq**********@murdoch.acc.Virginia.EDU...
Jonas Huckestein wrote:
>hello,
somehow i can't figure out, how to overload the [] operator for a
referenced object. if i have
class MyClass {
int operator[](int i) { return 1; };
You might want to consider using std::size_t instead of int as the
argument
type.
Yes you would think that, although in some cases this can lead to problems,
particularly when a conversion operator to another type that supports
operator[](int) exists (such as pointers). Say, for example, you have a
string class with a conversion operator to const char *
class String
{
public:
// yadda yadda yadda
char & operator[](size_t);
char operator[](size_t) const;
operator const char *() const;
};
void foo()
{
String s;
s[4]; // ambiguous call
}
s[4] wouldn't be ambiguous if String::operator[] accepted int instead of
size_t, because the literal 4 is int, which either has to be promoted to
size_t for String::operator[], or s has to be converted to const char* for
operator[](const char*, int). Now, if String::operator[] accepted int,
you'll never have this problem (not even if you pass it size_t).
I think it's best to leave the argument to operator[]s for array-like
indexing as ints (or perhaps even better: ptrdiff_t) rather than as other
integral types, as that's how the standard defines it's built-in types.
- Sylvester