ptr->hello(); /* 与 */ (*ptr).hello();
我正在学习 C++ 指针,->
运算符对我来说似乎很奇怪。 代替 ptr->hello();
人们可以写 (*ptr).hello();
因为它似乎也有效,所以我认为前者只是一个更方便的方式。
是这样还是有什么区别?
I was learning about C++ pointers and the ->
operator seemed strange to me. Instead ofptr->hello();
one could write (*ptr).hello();
because it also seems to work, so I thought the former is just a more convenient way.
Is that the case or is there any difference?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
-> 运算符只是语法糖,因为
(*ptr).hello()
是要键入的 PITA。 就 ASM 级别生成的指令而言,没有区别。 事实上,在某些语言中(我想到的是 D),编译器根据类型计算出所有内容。 如果你执行ptr.hello()
,它就会起作用,因为编译器知道 ptr 是一个指针并且没有 hello() 属性,所以你的意思必须是(*ptr ).hello()
。The -> operator is just syntactic sugar because
(*ptr).hello()
is a PITA to type. In terms of the instructions generated at the ASM level, there's no difference. In fact, in some languages (D comes to mind), the compiler figures everything out based on type. If you doptr.hello()
, it just works, because the compiler knows that ptr is a pointer and doesn't have a hello() property, so you must mean(*ptr).hello()
.其他人已经回答了有关内置指针的问题。 对于类,可以重载operator->(),operator&() 和operator*() 但不是operator.()。
这意味着对象的行为可能会根据您调用的语法而有所不同。
Others have already answered regarding built-in pointers. With regards to classes, it is possible to overload operator->(), operator&(), and operator*() but not operator.().
Which means that an object may act differently depending on which syntax you call.
当您必须链接函数调用时,可读性方面的主要优势就出现了,即:
我什至不会费心使用 * 运算符来执行此操作。
The main advantage in terms of readability comes when you have to chain function calls, i.e.:
I'm not even going to bother doing this with the * operator.
使用
'->'
运算符的唯一原因是使其更方便并避免出现如下错误:因为很容易忘记括号。
The only reason to have the
'->'
operator is to make it more convenient and save errors like:Because it is so easy to forget the parenthesis.
它们生成完全相同的机器代码,但对我来说,ptr->arg() 比 (*ptr).arg() 更容易阅读。
They generate the same exact machine code, but for me, ptr->arg() is much easier to read than (*ptr).arg().
这些替代语法模式是从 C 语言中采用的,您可能会从 教程中获得一些额外的理解关于 C 中的指针和数组,具体来说,第 5 章,指针和结构。
These alternate syntax modes are adopted from C, and you might get some additional understanding from A Tutorial on Pointers and Arrays in C, specifically, chapter 5, Pointers and Structure.