Difference Between Class Operators
I am reading into C++ a little bit and was wondering if someone could explain some differences of some of the class operators to me. The operators in question are:
* & . ->
I understand some of them, however, I fail to see the difference between some. For example:
*x
&x
x.y
(*x).y
x -> y
Can someone use 开发者_StackOverflow社区an example and explain a bit how they would differ?
Take this small structure as given for my samples:
struct MyStruct {
int y;
};
*x
dereferences the pointer x
. The return value is a reference to the object pointed to by x
:
MyStruct* x = ...;
MyStruct xval = *x;
// or
MyStruct& xref = *x;
// read up on references to understand the latter
&x
takes the address of x
. The result is therefore a pointer to x
.
MyStruct x;
MyStruct* pointer_to_x = &x;
x.y
accesses a member named y
in the object x
.
MyStruct x;
x.y = 5;
int a = x.y + 2;
// a==7
(*x).y
is a combination of the first and the third: the pointer is dereferenced, and the .
-operator is used to access a member of the object it points to.
a = (*pointer_to_x).y;
x->y
is (unless overridden by evil people) a shortcut for (*x).y
.
a = pointer_to_x->y;
*x
is the dereference operator, if you have a memoryAddress
, then *memoryAddress
is the respective object.
The converse, &x
is the reference operator, if you have an object
, then &object
provides the memory address.
For access variables, x->y
is basically a shortcut of (*x).y
, i.e. dereferencing and then accessing a member.
Keep reading! I'll give a nutshell of a couple but it might still not make sense until you really understand some of the underlying concepts.
*x is a dereferencing operator. It means that it treats 'x' as an address to memory, and it looks up what is in that memory location and returns that value. So if x = 100, *x looks up what's in memory address 100, and returns the value in that memory location.
&x returns the address that the variable x is stored in. Imagine again if x = 100, but the value 100 is stored at address 50. &x would return 50, x would return 100, and *x returns the value stored in memory address 100.
The others require a bit more explanation, but also a bit more understanding of classes and structures. I suggest you continue reading and doing more examples, as will probably help more than a long-winded explanation now.
*x
is the dereference
operator. That is, its the inverse of the &
operator - it gets the value of the memory pointed to by the pointer.
&
is an operator that returns the memory address of the variable.
x.y
means to access member y of x
x -> y
is a synonym for (*x).y
&
gets the memory address of an object*
gets the object pointed to by a memory address.
accesses a member of an object->
accesses a member from a pointer to an object
精彩评论