c++ - (->) arrow operator and (.) dot operator , class pointer -
in c++ know pointer of class use (->) arrow operator access members of class here:
#include <iostream> using namespace std; class myclass{ private: int a,b; public: void setdata(int i,int j){ a=i; b=j; } }; int main() { myclass *p; p = new myclass; p->setdata(5,6); return 0; }
then create array of "myclass".
p=new myclass[10];
but then, when go access myclass
members through (->) arrow operator, following error
base operand of '->' has non-pointer type 'myclass'
but while access class members through (.) operator works. these things make me confused. why array of class have use (.) operator.
you should read difference between pointers , reference might understand problem.
in short, difference is:
when create myclass *p
it's pointer , can access it's members ->
, because p
points memory location.
but call p=new myclass[10];
p
starts point array , when call p[n]
reference, members must accessed using .
.
if use p->member = smth
same if called p[0].member = smth
, because number in []
offset p
search next array member, example (p + 5).member = smth
same p[5].member = smth
Comments
Post a Comment