(->) arrow operator and (.) dot operator , class pointer

后端 未结 6 691
粉色の甜心
粉色の甜心 2021-01-31 21:55

In C++ we know that for a pointer of class we use (->) arrow operator to access the members of that class like here:

#include 
usi         


        
6条回答
  •  生来不讨喜
    2021-01-31 22:21

    you should read about difference between pointers and reference that might help you understand your problem.

    In short, the difference is:
    when you declare myclass *p it's a pointer and you can access it's members with ->, because p points to memory location.

    But as soon as you call p=new myclass[10]; p starts to point to array and when you call p[n] you get a reference, which members must be accessed using ..
    But if you use p->member = smth that would be the same as if you called p[0].member = smth, because number in [] is an offset from p to where search for the next array member, for example (p + 5)->member = smth would be same as p[5].member = smth

提交回复
热议问题