Sunday, August 2, 2009

What do these two pointer and address mean?

If I have these two C++ statement, can someone explain to me a plain english :





Tcl%26amp; tcl = Tcl::instance();





and





Tcl* tcl = Tcl::instance();





I know abit of programming. Just want to know what it actually mean and the differences.

What do these two pointer and address mean?
First of all let's get this straight, in this instance, the "%26amp;" is NOT the "address of" operator, it is used to declare that the variable is a "reference".





Now, as you've surmised, the two forms are similar, but there are a few key differences between using a pointer and a reference.





Tcl%26amp; tcl = Tcl::instance();





In this case, tcl is a reference to an instance of a Tcl object. To access members of tcl, you use the '.' operator (e.g. tcl.member). You treat tcl exactly as you would a local instance of a Tcl.





Tcl* tcl = Tcl::instance();





In this case, tcl is a pointer to an instance of a Tcl object. To access the members of tcl, you use the '-%26gt;' operator (e.g. tcl-%26gt;member).





Important differences:





With the pointer tcl, you can still point to something else





Tcl *p = Tcl::instance(); // p points to first instance


p = Tcl::instance(); // p now points to second instance, first intsance unchanged





With the reference it now looks like:





Tcl%26amp; p = Tcl::instance(); // p references first instance


p = Tcl::instance(); // p still references first instance


// but contents of first instance overwritten by second





There are a few other subtle differences, but I think the above hits the high points.
Reply:'%26amp;' refers to address of the variable name specified to the right of it.


'*' refers to the value at the address specfied by the variable to the right.
Reply:In your question Tcl is a class and tcl is an object.


Tcl %26amp;tcl=Tcl::instance() assign Tcl::instance() address into Tcl %26amp;tcl wlile Tcl *tcl=Tcl::instance() assign Tcl::instance() value into Tcl *tcl.

survey research

No comments:

Post a Comment