Why do pointers use -> instead of .? [duplicate]

2019-05-11 12:44发布

问题:

Possible Duplicate:
Why does C have a distinction between -> and . ?

Lets say that I have this structure:

struct movies
{
    string title;
    int year;
} my_movie, *ptrMovie;

Now I access my_movie like this: my_movie.year = 1999;
Now to access a pointer I must do this: ptrMovie->year = 1999;

Why do pointers use the -> operator and normal data types use the . operator? Is there any reason they couldn't both use the . operator?

回答1:

The . operator accesses a member of a structure and can operate only on structure variables. If you want to do this to a pointer, you first need to dereference the pointer (using *) and then access the member (using .). Something like

(*ptrMovie).year = 1999

The -> operator is a shorthand for this.



回答2:

The . operator is only valid for a struct or class. A pointer is not a struct or class, so you need to dereference your pointer to get the struct/class it is pointing to like this

(*ptrMovie).year

The member operator . has a higher precedence than the dereference operator *, so you need to enclose the dereferencing operation in parenthesis. Or you could do this

ptrMovie->year

Both are equivalent. The '->' operator is a shortcut for dereferencing your pointer and then accessing a struct member. It is less typing and a little nicer to use in my opinion. Apparently most people agree with me because that is the standard way to access struct members from a pointer to the struct in most code that I've seen. You especially appreciate the difference when you have to do multiple levels of indirection:

ptrToStruct->memberPtr->subMemberPtr->subsubPtr->subsubsubPtr->x

(*(*(*(*(ptrToStruct).memberPtr).subMemberPtr).subsubPtr).subsubsubPtr).x

Both of those statements are equivalent, but the first is easier to work with.



回答3:

If they both used . how could you differentiate between the pointer and the actual object? To me:

->

Reminds me of an arrow which points to something, so I find it great that -> is used.

Instead of typing (*myPointer). it is simplier to use myPointer->