Member pointer to array element

前端 未结 6 1241
野的像风
野的像风 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:43

    However, the compiler just complains about an "invalid use of non-static data member 'foo::b'"

    This is because foo::a and foo::b have different types. More specifically, foo::b is an array of size 2 of ints. Your pointer declaration has to be compatible i.e:

    int (foo::*aptr)[2]=&foo::b;
    

    Is it possible to do this at all (or at least without unions)?

    Yes, see below:

    struct foo
    {
      int a;
      int b[2];
    };
    
    int main()
    {
    
      foo bar;
    
      int (foo::*aptr)[2]=&foo::b;
      /* this is a plain int pointer */
      int *bptr=&((bar.*aptr)[1]);
    
      bar.a=1; 
      bar.b[0] = 2;
      bar.b[1] = 11;
    
      std::cout << (bar.*aptr)[1] << std::endl;
      std::cout << *bptr << std::endl;
    }
    

    Updated post with OP's requirements.

提交回复
热议问题