Difference between object-> function () and object.function () in C ++

Can someone explain the difference between doing something like:

a->height();

and

a.height();

Is there any difference?

+3
source share
8 answers

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.

+6
source

, , ->. " ". "" , , , , . , "", , . .

a->height(), a.height(). , a. , . ( ->) , . ( .) , . , .

-> * ., , a a->height(), (*a).height(). , a->height() (*a).height(). : ( , ->)

+5

, "a" . :

SomeClass a;

"a" , ".". .

:

SomeClass * a;
a = [some expression that produces a pointer to a SomeClass object];

"a" POINTER TO , . "- > ".

( , - , - .)

+2

, , , . , , - .

+2

, a , :

:

a->height();

:

(*a).height();

, ( ).
→ , , , .

person->body()->arm(right)->hand()->finger(index)->ring()->activate();

, :

(*(*(*(*(*(*person).body()).arm(right)).hand()).finger(index)).ring()).activate();

- (*) , . → - .

+2

operator->, , , , . , a->foo() (*a).foo().

, a->foo() , a , 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, - , , , "" - .

+2

, , . , , a operator->, . a.name() name(), a->name() name() , ( , , "" , , , ). , .

0

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.

-2
source

All Articles