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

后端 未结 6 858
粉色の甜心
粉色の甜心 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:15

    myclass *ptr;
    
    ptr = new myclass();     // ptr points to a single object
    ptr->doSomething();      // calls doSomething on the object _pointed to_
    
    ptr = new myclass[10];   // ptr points to multiple objects
    ptr->doSomething();      // calls doSomething on the first object _pointed to_
    (ptr+1)->doSomething();  // calls doSomething on the second object _pointed to_
    
    auto val = ptr[2];       // fetches a reference to the second _object_ to val.
    val.doSomething();       // calls doSomething on the _object reference_ val.
    

    In other words, when indexing the array to fetch the n'th element, you're not fetching a pointer to the n'th element, you're fetching a reference to the actual object, and the members of that need to be accessed using . syntax.

提交回复
热议问题