Member pointer to array element

前端 未结 6 1225
野的像风
野的像风 2021-02-04 06:29

It\'s possible to define a pointer to a member and using this later on:

struct foo
{
  int a;
  int b[2];
};

int main() {
foo bar; int foo::*

6条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-04 06:58

      typedef int (foo::*b_member_ptr)[2];
      b_member_ptr c= &foo::b;
    

    all works.

    small trick for member and function pointers usage.
    try to write

    char c = &foo::b; // or any other function or member pointer
    

    and in compiller error you will see expected type, for your case int (foo::*)[2].

    EDIT
    I'm not sure that what you want is legal without this pointer. For add 1 offset to your pointer you should get pointer on array from your pointer on member array. But you can dereference member pointer without this.

提交回复
热议问题