“->”是什么意思? C++ 中的运算符意味着什么?
有人可以向我解释一下“->”是什么吗?在C++中意味着?
如果可以的话,举一些例子,它们可以帮助我更好地理解。 谢谢。
Could someone explain to me what the "->" means in C++?
Examples if you can, they help me understand better.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是取消引用然后进行属性访问(或方法调用)的快捷方式。
在代码中,以下是这种等价性的一些示例:
当您有很长的序列时,这尤其方便。例如,如果您有一个单链表数据结构,其中每个元素都有一个指向下一个元素的指针,则以下是查找第五个元素的等效方法(但其中一种看起来更好):
It's a shortcut for dereference followed by property access (or method invocation).
In code, here are some examples of this equivalence:
This is especially convenient when you have a long sequence of these. For example, if you have a singly linked list data structure in which each element has a pointer to the next, the following are equivalent ways of finding the fifth element (but one looks much nicer):
它通常被称为“成员访问”运算符。基本上,
a->b
是一种更好的编写(*a).b
的方式。您可以将a->b
视为“访问a
指向的对象中的b
成员/函数”。您可以大声朗读(或自己思考)“a
成员访问b
”。在我刚刚检查的结构化 C++ 代码的随机样本中(来自不同人编写的几个不同项目),10% 的代码行(不包括标头)包含至少一个成员访问运算符。
It's often called the "member access" operator. Basically,
a->b
is a nicer way to write(*a).b
. You can think ofa->b
as "access theb
member/function in the objecta
points to". You can read it aloud (or think it to yourself) as "a
member accessb
".In a random sample of structured C++ code I just checked (from several different projects written by different people), 10% of lines of code (not counting headers) contained at least one member access operator.
->
运算符与 LHS 上的指针(或类似指针的对象)以及 RHS 上的结构或类成员一起使用 (lhs->rhs
) 。它通常相当于(*lhs).rhs
,这是访问成员的另一种方式。如果你忽略德米特定律,需要写成lhs->mid->rhs
会更方便(通常比(*(*lhs).mid 更容易阅读) ).rhs
)。您可以重载
->
运算符,智能指针经常这样做。AFAIK您不能重载.
运算符。The
->
operator is used with a pointer (or pointer-like object) on the LHS and a structure or class member on the RHS (lhs->rhs
). It is generally equivalent to(*lhs).rhs
, which is the other way of accessing a member. It is more convenient if you ignore the Law of Demeter and need to writelhs->mid->rhs
(which is generally easier to read than(*(*lhs).mid).rhs
).You can overload the
->
operator, and smart pointers often do.AFAIKYou cannot overload the.
operator.