C++中(*a).b与a->b的区别及考试扣分争议咨询
(*a).b and a->b in C++ Hey there, I totally get why this is so frustrating—especially when your shot at switching from the web stack to the application stack rides on that near-perfect grade. Let’s break this down clearly, so you can address the grading dispute and solidify your C++ knowledge at the same time.
First, the Core Truth: They’re Semantically Equivalent (for Plain Pointers)
When a is a plain pointer to a class, struct, or union in standard C++, (*a).b and a->b do exactly the same thing: they access the member b of the object that a points to. The -> operator is actually just syntactic sugar for dereferencing the pointer first with *, then accessing the member with ..
The C++ standard explicitly defines this equivalence—there’s no functional difference between the two when working with regular pointers. So from a strict syntax and behavior standpoint, your (*a).b code wasn’t wrong.
Why Might Your Teacher Have Marked It Wrong?
There are a few likely reasons here, none of which make your code syntactically incorrect, but they tie into coding best practices:
- Readability & Industry Norms:
a->bis universally preferred in professional C++ code because it’s cleaner, especially with nested members. Compare(*(*(*a).b).c).dtoa->b->c->d—the latter is far easier to parse at a glance. Many instructors enforce this as part of teaching good coding habits, even if it’s not a strict syntax error. - Potential for Typos: Using
(*a).bintroduces a higher risk of mistakes, like forgetting parentheses (writing*a.binstead, which would dereferencea.binstead ofa—that is a syntax error). Your teacher might be penalizing the style to push you toward safer, more readable code. - Edge Cases with Overloaded Operators: If
awasn’t a plain pointer (e.g., a smart pointer or a custom class with overloadedoperator*/operator->), there could be subtle differences—but this is rare in a midterm context, and given your web/.NET background, you’re probably using plain pointers here.
How to Address the Grading Dispute
- Talk to Your Teacher: Approach them politely, explain your situation (needing the perfect grade for a stack shift), and ask for clarification on why the code was marked wrong. Reference the C++ standard’s equivalence of the two syntaxes—most instructors will appreciate you engaging with the material deeply.
- Adjust for Future Assignments: Even if you’re right about the syntax, adopting
a->bwill align you with industry standards, which is crucial for your upcoming role switch. It’s a small habit that will make your code feel more idiomatic to C++ developers.
内容的提问来源于stack exchange,提问作者Voltex

