指针解引用运算符( (*) 与 -> )
之间有一般的区别吗
(*ptr).method()
做与
ptr->method()
我在另一个问题的评论中看到这个问题并认为我会在这里问 ?尽管我刚刚记得 C++ 中几乎每个运算符都可以重载,所以我想答案将取决于。但总的来说,做其中一种与另一种有区别吗?
Is there a general difference between doing
(*ptr).method()
vs
ptr->method()
I saw this question in a comment on another question and thought I would ask it here. Although I just remembered that pretty much every operator in C++ can be overloaded, so I guess the answer will depend. But in general, is there a difference between doing one versus the other?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
正如“jamesdlin”已经指出的,
*
和->
运算符可以为类类型重载。然后两个表达式
(*ptr).method()
和ptr->method()
可以产生不同的效果。但是,对于内置运算符,这两个表达式是等效的。
当您跟踪指针链时,
->
运算符更方便,因为.
的优先级高于*
,因此需要很多无法理解的括号。考虑:
与
As "jamesdlin" already noted, the
*
and->
operators can be overloaded for class types.And then the two expressions
(*ptr).method()
andptr->method()
can have different effect.However, for the built-in operators the two expressions are equivalent.
The
->
operator is more convenient when you're following a chain of pointers, because.
has higher precedence than*
, thus requiring a lot of ungrokkable parentheses.Consider:
versus
对于原始指针类型,它们是等效的。
是的,对于一般类型,答案确实是“这取决于”,因为类可能会重载
operator*
和operator->
以获得不同的行为。For raw pointer types, they are the equivalent.
And yes, for general types, the answer is indeed "it depends", as classes might overload
operator*
andoperator->
to have different behaviors.是的。
ptr->method()
比(*ptr).method()
短两个字符。它也更漂亮。
Yes.
ptr->method()
is two characters shorter than(*ptr).method()
.It is also prettier.
C++ 标准 5.2.5/3:
对于非指针值,运算符可能会重载。
C++ Standard 5.2.5/3:
For non-pointer values operators could be overloaded.
不! (除非
->
和*
显式重载以执行不同的功能)ptr->method()
和(*ptr ).method()
是等效的。No! (unless
->
and*
are explicitly overloaded to perform different functions)ptr->method()
and(*ptr).method()
are equivalent.很抱歉挖掘这篇文章,但即使 OP 中的表达式对于原始指针类型是等效的,我认为除了已经说过的所有内容之外,在 C++ 中至少还有一个重要的区别需要提及:
来自 Wikipedia (http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B #cite_note-arrowptr-6):
这意味着
->
预计返回一个可解引用类型,而*
预计返回一个已解引用类型类型,因此此“链接”仅适用于->
。Sorry to dig this post, but even though the expressions in the OP are equivalent for raw pointer types, I think there is at least one important difference to be mentioned in C++, in addition to everything that has been said:
From Wikipedia (http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#cite_note-arrowptr-6):
This implies that
->
is expected to return a dereferenceable type, whereas*
is expected to return a dereferenced type, and therefore this "chaining" applies to->
only.->
序列充当其指向某物的视觉指示符。两个操作员执行完全相同的操作顺序。The
->
sequence serves as a visual indicator that it is pointing to something. Both operators do the exact same sequence of operations.它们是同义词。后者是前者的简写。
They are synonyms. The latter is a shorthand for the former.