Possible Duplicate:
what is the difference between (.) dot operator and (->) arrow in c++
I'm trying to learn c++, but what I don't understand is the different between "->" and "." when calling a method.
For example, I have seen something like class->method(), and class.method().
Thanks.
In a normal case, a->b
is equivalent to (*a).b
. If a
is a pointer, ->
dereferences it before accessing the element.
The ->
operator calls a method on the object pointed to by a pointer.
The .
operator calls a method on an object itself.
If a
is a pointer, a->b()
is equivalent to (*a).b()
.
You use -> when the thing on the left is a pointer to an object. You use '.' when the thing on the left is the object itself.
When your calling a method through a pointer, you use ->
; otherwise, use .
.
Example:
MyClass* obj = new MyClass();
obj->myMethod();
MyClass obj2;
obj2.myMethod();
It is maybe a bit irritating at first but C/C++ differenciates calling a method through the use of a pointer (use of ->
) or through the use of a variable/reference (use of .
). So the type of variable you use decides whether you call with the one or with the other option.
Note that in many other programming languages (Java, C#, ...) this is not the case.
You will never see class.method()
or class->method()
in C++. What you will see is object.method()
, obj_ptr->method()
or class::method()
. When you make an object of a class, you use the .
operator, when refering to a pointer to an object, you use ->
and when calling a static method directly without making an object, you use ::
. If you have a class a_class
like below, then:
class a_class
{
public:
void a_method()
{
std::cout<<"Hello world"<<std::endl;
}
static void a_static_method()
{
std::cout<<"Goodbye world"<<endl;
}
}
int main()
{
a_class a_object = a_class();
a_class* a_pointer = new a_class();
a_object.a_method(); //prints "Hello world"
a_object->a_method(); //error
a_object::a_method(); //error
a_pointer.a_method(); //error
a_pointer->a_method(); //prints "Hello world"
a_pointer::a_method(); //error
*a_pointer.a_method(); //prints "Hello world"
*a_pointer->a_method(); //error
*a_pointer::a_method(); //error
a_class.a_method(); //error
a_class->a_method(); //error
a_class::a_method(); //error because a_method is not static
a_class.a_static_method(); //error
a_class->a_static_method(); //error
a_class::a_static_method(); //prints "Goodbye world"
}
精彩评论