2

可能重复:
ptr->hello(); /* VERSUS */ (*ptr).hello();

我正在学习 C++,我的问题是使用箭头运算符 ( ) 或取消引用调用函数->的指针之间是否有任何区别。*

这两个案例说明了我的问题。

Class* pointer = new Class();
(*pointer).Function();         // case one
pointer->Function();           // case two

有什么区别?

4

2 回答 2

6

如果运算符*->没有重载,则两个版本的效果相同。

于 2012-11-19T13:49:56.350 回答
3

Given

Class* pointer = new Class();

Then

(*pointer).Function();         // case one

dereferences the pointer, and calls the member function Function on the referred to object. It does not use any overloaded operator. Operators can't be overloaded on raw pointer or built-in type arguments.

pointer->Function();           // case two

This does the same as the first one, using the built-in -> because pointer is a raw pointer, but this syntax is better suited for longer chains of dereferencing.

Consider e.g.

(*(*(*p).pSomething).pSomethingElse).foo()

versus

p->pSomething->pSomethingElse->foo()

The -> notation is also more obvious at a glance.

于 2012-11-19T13:59:06.320 回答