C++中的 . -> ::

C++中的 . -> ::

Dot, Arrow,Colon

a::b is only used if b is a member of the class (or namespace) a. That is, in this case a will always be the name of a class (or namespace).

a.b is only used if b is a member of the object (or reference to an object) a. So for a.b, a will always be an actual object (or a reference to an object) of a class.

a->b is, originally, a shorthand notation for (*a).b it is a combination of dereferencing and member access.

However, -> is the only of the member access operators that can be overloaded, so if a is an object of a class that overloads operator-> (common such types are smart pointers and iterators), then the meaning is whatever the class designer implemented. To conclude: With a->b, if a is a pointer, b will be a member of the object the pointer a refers to. If, however, a is an object of a class that overloads this operator, then the overloaded operator function operator->() gets invoked.

a :: b 当b是一个类或namespace的成员,a是那个对象或namespace

a.b 当b是一个对象a的成员,对于a.b,a总是那个类的对象。

a->b 和 (*a).b 可以互换, a是一个指针,b则是指针指向的对象

 include 

using namespace std;

class SomeClass{
public
        int mydata;
        bool someTruth;
        SomeClass(){
              mydata = 0;
              someTruth = false;
       }
};

int main(){

    SomeClass mySomeClass;  // Not a pointer...
    SomeClass *pSomeClass;  // we defined the pointer.
    pSomeClass = new SomeClass; // we allocate the pointer. 
   
    // accessing the stuff beyond the pointer.
    pSomeClass->mydata = 10; // we assigned mydata, the object's member, to 10.
    pSomeClass->someTruth = true;  // now we made someTruth, the object's member, to true
    // the previous too lines are basically similar to
    mySomeClass.mydata = 10;
    mySomeClass.someTruth = true;

    // assign accessing the member of the pointer of SomeClass
    if(pSomeClass->someTruth == true)
    {
           cout << "pSomeClass->someTruth was True" << endl;
    }

    // clean up the pointer
    delete pSomeClass;
    
    return 0;

问题与思考

什么时候使用pointer,什么时候直接定义?

C++中的 . -> ::_第1张图片

你可能感兴趣的:(C++中的 . -> ::)