when I have a pointer like:
MyClass * pRags = new MyClass;
So i can use
pRags->foo()
or
(*pRags).foo()
to call foo.
Why t开发者_JAVA技巧hese 2 are identical? and what is *pRags?
Thank you
Why are these two identical?
They are equivalent because the spec says they are equivalent. The built-in ->
is defined in terms of the built-in *
and .
.
What is
*pRags
?
It is the MyClass
object pointed to by pRags
. The *
dereferences the pointer, yielding the pointed-to object.
For more information, consider picking up a good introductory C++ book.
In addition to the other answers, the '->' is there for convenience. Dereferencing a pointer to an object every time you access a class variable for function is quite ugly, inconvenient, and potentially more confusing.
For instance:
(*(*(*car).engine).flux_capacitor).init()
vs
car->engine->flux_capacitor->init()
pRags->foo()
is defined as syntactic sugar that is equivalent to (*pRags).foo()
.
the *
operator dereferences a pointer. That is, it says that you're operating on what the pointer points to, not the pointer itself.
The ->
is just a convenient way to write (*).
. and *pRags
is the object at the address stored in pRags
.
- Yes they are identical.
->
was included in C (and thus inherited into C++) as a notational convenience. *
in that context is used to dereference a pointer.
Unary *
is known as the dereferencing operator. Dereferencing a pointer turns a T*
into a T&
; dereferencing an object invokes that object type's unary operator*
on that object value if one is defined, or gives an error otherwise.
(*pRags)
that goes through the pointer pRags
and get you whole object, so on that you could use regular dot notation .
.
pRags is a pointer of type MyClass. Just like you can have pointers for primitive data types, e.g. int ptr, you can also have pointers to objects and in this case represented by pRags. Now accessing the object "members" is done using the arrow operator (->) or you can use the "." and dereference "*" to access the object's member values. Here a member is a variable inside MyClass. So, foo() would have a definition inside MyClass.
精彩评论