本文翻译自:What is the difference between the dot (.) operator and -> in C++? [duplicate]
This question already has an answer here: 这个问题在这里已有答案:
What is the difference between the dot (.) operator and -> in C++? 点(。)运算符和C ++中的 - >有什么区别?
#1楼
参考:https://stackoom.com/question/5CDd/点-运算符和C-中的-有什么区别-重复
#2楼
The .
的.
operator is for direct member access. 运营商是直接成员访问。
object.Field
The arrow dereferences a pointer so you can access the object/memory it is pointing to 箭头取消引用指针,以便您可以访问它指向的对象/内存
pClass->Field
#3楼
The arrow operator is like dot, except it dereferences a pointer first. 箭头操作符就像点,除了它首先取消引用指针。 foo.bar()
calls method bar()
on object foo
, foo->bar
calls method bar
on the object pointed to by pointer foo
. foo.bar()
调用对象foo
上的方法bar()
, foo->bar
调用指针foo
指向的对象上的方法bar
。
#4楼
Use ->
when you have a pointer. 当你有一个指针时使用->
。 Use .
使用.
when you have structure (class). 当你有结构(类)。
When you want to point attribute that belongs to structure use .
当您想要指向属于结构使用的属性时.
: :
structure.attribute
When you want to point to an attribute that has reference to memory by pointer use ->
: 如果要指向通过指针引用内存的属性,请使用->
:
pointer->method;
or same as: 或者相同:
(*pointer).method
#5楼
The target. 目标。 dot works on objects; dot适用于物体; arrow works on pointers to objects. 箭头适用于指向对象的指针。
std::string str("foo");
std::string * pstr = new std::string("foo");
str.size ();
pstr->size ();
#6楼
Dot operator can't be overloaded, arrow operator can be overloaded. 点运算符不能重载,箭头运算符可以重载。 Arrow operator is generally meant to be applied to pointers (or objects that behave like pointers, like smart pointers). 箭头操作符通常用于指向指针(或类似指针的对象,如智能指针)。 Dot operator can't be applied to pointers. 点运算符不能应用于指针。
EDIT When applied to pointer arrow operator is equivalent to applying dot operator to pointee (ptr->field is equivalent to (*ptr).field) 编辑当应用于指针箭头时,运算符相当于将点运算符应用于指针对象(ptr->字段相当于(* ptr).field)