Pay attention to
operator precedence
http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Operator_precedence
The [] has a higher precedence than *, so it gets applied first.
In C (and hence in C++), the [] operator is a synonym for applying * with an offset, just as you have listed:
1 2
|
int xs[ 12 ];
xs[ 2 ] == *(xs + 2)
|
Hence, when the compiler sees line 1 it converts it to line 2:
1 2
|
string* str = &my_string;
*str[0] == *( *(str + 0) )
|
Naturally, as the first dereference is a pointer, it works fine. The problem is that you are left trying to dereference an
object, not a pointer:
1 2
|
...
*my_string == fooey -- i cannot dereference an object
|
In C++, objects can
overload nearly all of the standard operators to make them
appear like simple objects. My canonical example is the "point" class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
struct point_t
{
int x, y;
point_t( int x = 0, int y = 0 ): x( x ), y( y ) { }
};
int main()
{
point_t a( 10, 12 );
point_t b( -7, 24 );
// now I want to add them together
point_t c = a + b; // argh! The compiler complains that this doesn't work!
|
And of course it complains -- the computer doesn't know how to combine two points. I can go the long way and say
c = point_t( a.x + b.x, a.y + b.y );
but that exposes details of the point class everywhere it is used. Instead, I'll overwrite the + operator to do my bidding:
7 8 9 10
|
point_t operator + ( const point_t& lhs, const point_t& rhs )
{
return point_t( lhs.x + rhs.x, lhs.y + rhs.y );
}
|
Now of course the attempt to add two points on line 18 above will work just fine. (Because the computer knows how to do it now, and the user is blissfully spared the internal workings of the class just to add two points together.)
The
std::
string class does the same thing to the [] operator. Since a
string is not an array pointer (it is an object) it cannot be dereferenced. But it is desirable to treat it
as if it were. Hence, anywhere you have
my_string[ n ]
the compiler says, "I know how to do that," and does it properly using the fancy function provided by the STL to access one character in the string.
Hope this helps.