Can someone explain the difference between doing something like:
a->height();
and
a.height();
Is there any difference?
In the first example, a is a pointer to an object; in the second example, this is the object itself (or a reference to the object). At the lowest level, there is no clear difference between them.
, , ->. " ". "" , , , , . , "", , . .
->
a->height(), a.height(). , a. , . ( ->) , . ( .) , . , .
a->height()
a.height()
a
.
-> * ., , a a->height(), (*a).height(). , a->height() (*a).height(). : ( , ->)
*
(*a).height()
, "a" . :
SomeClass a;
"a" , ".". .
:
SomeClass * a; a = [some expression that produces a pointer to a SomeClass object];
"a" POINTER TO , . "- > ".
( , - , - .)
, , , . , , - .
, a , :
(*a).height();
, ( ).→ , , , .
person->body()->arm(right)->hand()->finger(index)->ring()->activate();
, :
(*(*(*(*(*(*person).body()).arm(right)).hand()).finger(index)).ring()).activate();
- (*) , . → - .
operator->, , , , . , a->foo() (*a).foo().
operator->
a->foo()
(*a).foo()
, a->foo() , a , foo, - :
foo
struct xC { struct Member { void foo(){printf("xC::Member::foo\n");}; }; Member a; Member* operator->() { return &a; } // following function doesn't really make sense. void foo() { printf("xC::foo\n");}; }; int main(){ xC x; x.foo(); // prints "xC::foo". x->foo();// prints "xC::Member::foo" }
stl- operator->. Stroustrup, - , , , "" - .
, , . , , a operator->, . a.name() name(), a->name() name() , ( , , "" , , , ). , .
a.name()
name()
a->name()
It all comes down to how readable you want the code itself and how fast you want it. At the lowest level in assembler, it comes down to pushing / pulling onto the stack. In real life today, with fast computers / MCUs, that doesn't matter. This is the programming style that you use. Both methods are good, but do not mix them. This can make reading difficult for other programmers.