Member pointer to array element

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

    The problem is that, accessing an item in an array is another level of indirection from accessing a plain int. If that array was a pointer instead you wouldn't expect to be able to access the int through a member pointer.

    struct foo
    {
      int a;
      int *b;
    };
    
    int main()
    {
    
      foo bar;
      int foo::* aptr=&(*foo::b); // You can't do this either!
      bar.a=1;
      std::cout << bar.*aptr << std::endl;
    }
    

    What you can do is define member functions that return the int you want:

    struct foo
    {
      int a;
      int *b;
      int c[2];
    
      int &GetA() { return a; } // changed to return references so you can modify the values
      int &Getb() { return *b; }
      template 
      int &GetC() { return c[index]; }
    };
    typedef long &(Test::*IntAccessor)();
    
    void SetValue(foo &f, IntAccessor ptr, int newValue)
    {  
        cout << "Value before: " << f.*ptr();
        f.*ptr() = newValue;
        cout << "Value after: " << f.*ptr();
    }
    
    int main()
    {
      IntAccessor aptr=&foo::GetA;
      IntAccessor bptr=&foo::GetB;
      IntAccessor cptr=&foo::GetC<1>;
    
      int local;
      foo bar;
      bar.a=1;
      bar.b = &local;
      bar.c[1] = 2;
    
      SetValue(bar, aptr, 2);
      SetValue(bar, bptr, 3);
      SetValue(bar, cptr, 4);
      SetValue(bar, &foo::GetC<0>, 5);
    }
    

    Then you at least have a consistent interface to allow you to change different values for foo.

提交回复
热议问题