difference between -> and . for member selection operator [duplicate]
开发者_运维知识库Possible Duplicate:
what is the difference between (.) dot operator and (->) arrow in c++
in this book i have I'm learning pointers, and i just got done with the chapter about OOP (spits on ground) anyways its telling me i can use a member selection operator like this ( -> ). it sayd that is is like the "." except points to objects rather than member objects. whats the difference, it looks like it is used the same way...
Where:
Foo foo;
Foo* pfoo = &foo;
pfoo->mem is semantically identical to (*pfoo).mem.
Or, put another way: foo.mem is semantically identical to (&foo)->mem.
Yeah, it actually does the same thing but for different kind of variables.
If you have a pointer you have to use ->, while if you have a real value you will use ..
So for example
struct mystruct *pointer;
struct mystruct var;
pointer->field = ...
var.field = ...
That's not hard at all. Just remember that with a pointer you will need ->, and . otherwise.
You only use -> when the variable is a pointer to your object:
A* a = new A;
a->member();
Use "." when it's not a pointer:
A a;
a.member();
struct S
{
int a, b;
};
S st;
S* pst = &st;
st.a = 1; // . takes an object (or reference to one)
pst->b = 2; // -> takes a pointer
When you have an object instance (MyObject object;), you use the . to access it members (methods, properties, fields, etc), like this: object.Member.
When you have a pointer to an object instance (MyObject* pObject = new MyObject();), you need to dereference the pointer, before you can access the object members. To dereference a pointer you use the * operator. Thus, when you combine both, you get something like this: (*pObject).Member.
Of course, this is not readable, so the compilers take the -> as a shorthand for it. Thus, it becomes pObject->Member.
maybe this example will help
object o;
object *p = &o; // pointer to object
o.member; // access member
p->member; // access member through pointer
You use -> to dereference the pointer, when you access members via pointer, you use . when you access directly on member.
class A
{
public:
int x;
void g() {};
};
A a;
a.x
a.g();
A * ap = new A();
ap->x;
ap->g();
and you can dereference pointer and then use .:
(*ap).x;
(*ap).g();
加载中,请稍侯......
精彩评论