subscript operator on pointers

后端 未结 4 2330
醉梦人生
醉梦人生 2021-02-19 09:31

If I have a pointer to an object that has an overloaded subscript operator ([]) why can\'t I do this:

 MyClass *a = new MyClass();
 a[1];

4条回答
  •  不知归路
    2021-02-19 09:57

    Because a is type pointer to a MyClass and not a MyClass. Changing the language to support your desired use would make many other language semantics break.

    You can get the syntactic result you want from:

    struct foo {
        int a[10];
        int& operator [](int i) { return a[i]; }
    };
    
    main() {
        foo *a = new foo();
        foo &b = *a;
        b[2] = 3;
    }
    

提交回复
热议问题