In C++, the ->
and .
operators are used to access members of a class or structure, but they are used in different contexts.
-
->
Operator:- Used with pointers to objects.
- It is a shorthand for dereferencing a pointer and then accessing a member.
- Example:
pointer->member
is equivalent to(*pointer).member
.
MyClass* objPtr = new MyClass();
objPtr->someFunction(); // Access member function using ->
objPtr->someVariable = 42; // Access member variable using ->
-
.
Operator:- Used with objects (not pointers).
- Directly accesses members of the object.
- Example:
object.member
.
MyClass* objPtr = new MyClass();
objPtr->someFunction(); // Access member function using ->
objPtr->someVariable = 42; // Access member variable using ->
In summary, use ->
when you are working with pointers to objects, and use .
when you are working with objects directly. The choice between them depends on whether you have a pointer to an object or the object itself.
补充
struct dinode* dip; 解释为什么 dip[i] 就不是 pointer 了 但是 (dip + i) 还是 pointer?
在C语言中,dinode是一个结构体类型,而dip是一个指向struct dinode的指针。当你写下struct dinode* dip;时,你创建了一个指针,可以指向一个struct dinode类型的变量。
现在,让我们来看一下dip[i]和(dip + i)的区别:
dip[i]:这实际上是对指针dip进行索引操作。在C语言中,dip[i]等同于*(dip + i),它是指针算术运算的一种语法糖。这个表达式表示取指针dip指向的内存地址加上i个struct dinode的大小的偏移,然后从那个位置取值。因此,dip[i]是一个struct dinode类型的变量。
(dip + i):这是指针算术运算的一种形式,表示从指针dip所指向的位置开始,向后移动i个struct dinode的大小的偏移。这仍然是一个指向struct dinode类型的指针。换句话说,(dip + i)是一个指向数组中第i个元素的指针。
因此,虽然dip[i]和(dip + i)都可以用于访问数组中的元素,但前者是元素本身,而后者是指向元素的指针。