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

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

    Perhaps its insightful to consider that, given

    myclass obj;
    auto p = &obj;  // avoid `new` with plain pointers. That combination is
                   //  safer replaced by unique_ptr or std::vector.
    

    the following will all work and are equivalent:

    p->setdata(5, 6);
    (*p).setdata(5, 6);
    p[0].setdata(5, 6);
    0[p].setdata(5, 6);
    

    Showing that [] is really a pointer-dereferencing operator, just with the extra functionality that you can add offsets into a plain C-array.

    It's generally questionable to use C-arrays in C++ code; the obvious alternative to your example is std::vector:

    std::vector array(10);
    

    Here, array[n] can be used much like previously p[n], but

    • You don't get any stupid pointer-ideas, because there are no pointers in the interface
    • You get proper automatic memory management, i.e. when the array goes out of scope it automatically deletes the objects and its memory
    • You can get bounds-checks if you want (array.at(n))
    • You can easily loop over the whole array, with (C++11) for(auto& obj: array){...}.

提交回复
热议问题