Operator '.' vs '->' in C++ [duplicate]
Possible Duplicate:
What is the difference between the dot (.) operator and -> in C++?
What is the difference between the two? When do you use one instead of the other?
There was once I tried to use '->' instead of '.' and I got "left operand has 'class' type, use '.'" error, what does it mean?
The .
allows you to access members of a class. thingy.member
, for example.
If you have a pointer to your class, say pThingy
, you need to dereference it in order to access the members. Like (*pthingy).member
.
A shortcut to the dereference/access combination is ->
: pThingy->member
.
All these answers are somewhat correct in a narrow scope. You can use the -> operator even if you don't have a pointer because you can overload it. Take a look at smart pointers:
class A
{
public:
void foo();
}
class SmartPtr
{
public:
SmartPtr (A& obj)
{
instance = obj;
}
A instance;
A operator-> ()
{
return instance;
}
};
Then you can do:
A a;
SmartPtr smart(a);
smart->foo();
so you can use -> even though SmartPtr is not a pointer to an object of type SmartPtr.
This answer is in addition to previous ones, as they might be misleading. In a simple case, they are all correct. Note that the dot(.) operator cannot be overloaded.
.
to be use if the object is of type T
. ->
if the object is of type T*
.
class foo {};
foo obj;
obj
type is foo
and it lies on stack. So, to access it's members .
operator needs to be used.
foo *hObj = new foo();
hObj
is a pointer to the object. So, to access it's members ->
operator needs to be used.
You use object.property
to get the property of an object. However if you have a pointer to an object (let's call it pointer_to_object
) then you will use ->
to access its properties: pointer_to_object->property
The reason why you got the error is because the statement pointer_to_object->property
will try to dereference first to the actual object and then access its property. If the variable is not a pointer to an object, then you get the error.
x->blah
is a nice why of writing (*x).blah
. That is it dereferences a pointer, and then accesses the member blah
. If x isn't a pointer than you have a compile time error.
If a is a pointer (or an object proposing "pointer semantics") think to a->b
as (*a).b
In more general term, if a
is not a pointer they are two operators: ->
is overridable (so what it does depends on the class it applies, note class as a type, not pointer to a class: see above for that), the other is the non overridable member selection (meaningless for non composite types), so
a->b
means "access the b member trough the pointer returned by A::operator->()
called on a
",
and a.b
means "access the b
member of a
".
精彩评论