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 <iostream>

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,什么时候直接定义?

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,934评论 0 23
  • 『箭与盾』 造箭之人,注定杀念太重,因为唯恐箭不伤人 造盾之人,注定福报多多,因为唯恐盾不护人 一念之差·天壤之别...
    5de7b70be210阅读 98评论 0 0
  • 蝶恋花兮花恋蝶, 美人花间舞长娟; 凤尾蝶兮躇指尖, 婷婷玉立丽人心; 灵蝶幻兮入梦蝶, 皓月解梦桃花开。
    知名不具留的ai阅读 141评论 0 1
  • 文图/静仁 车灯一关 淘气的熊孩子都安静下来 只剩火车与铁轨的摩擦声 世界一旦寂静 你就很难推敲 这黑夜是该感怀还...
    赵静仁阅读 516评论 0 1
  • 花灯忍放焰终熄,烟火落冰肌。长街执袖紧随,公子语曾讥。 君故去,雨湿衣,泪决堤。家仇国恨,恩情难偿,来世相惜。 —...
    林香砌阅读 302评论 3 5