关于结构体成员指针:(*pmovie).title与*(pmovie.title)的区别求解
(*pmovie).title and *(pmovie.title) in C++ Hey there! This is a super common gotcha that all comes down to C++ operator precedence—the order the compiler uses to evaluate operations. Let’s break this down step by step with a concrete example to make it crystal clear.
First, let’s assume we’re working with a simple Movie struct like this:
#include <string> struct Movie { std::string title; int release_year; }; // And a pointer pointing to an instance of this struct: Movie* pmovie = new Movie{"The Matrix", 1999};
1. (*pmovie).title – The Correct Way to Access a Struct Member via Pointer
- The parentheses
()force the compiler to evaluate*pmoviefirst. This dereferences the pointer, meaning we get the actualMoviestruct object thatpmovieis pointing to. - Next, we use the
.member access operator to grab thetitlemember of that struct. This works exactly as you’d expect—we end up with the string"The Matrix".
As a handy shortcut, C++ gives us pmovie->title which does the exact same thing as (*pmovie).title—it’s the standard, cleaner way to write this in practice.
2. *(pmovie.title) – This Will (Almost Always) Fail to Compile
Here’s where the precedence rule trips people up: the . member access operator has higher priority than the * dereference operator. That means the compiler tries to evaluate pmovie.title first, before it ever gets to the *.
But wait—pmovie is a pointer (Movie*), not a Movie struct instance. Pointers don’t have a title member! The compiler will throw an error like:
error: 'Movie*' has no member named 'title'
Even if pmovie was a struct that had a title member (say, a different struct containing a pointer), *(pmovie.title) would dereference whatever pmovie.title points to—not the title of the original Movie struct we care about. In your original context, this is almost certainly a mistake.
Key Takeaway
Always remember: . and -> have higher precedence than *. If you’re using * to dereference a struct pointer before accessing a member, you must wrap the dereference in parentheses to override the default precedence. Or better yet, use the -> syntax—it avoids this confusion entirely.
内容的提问来源于stack exchange,提问作者Peter Ye

