点(。)运算符和C ++中的 - >有什么区别? [重复]

本文翻译自: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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值