Member pointer to array element

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

    I'm not sure if this will work for you or not, but I wanted to do a similar thing and got around it by approaching the problem from another direction. In my class I had several objects that I wanted to be accessible via a named identifier or iterated over in a loop. Instead of creating member pointers to the objects somewhere in the array, I simply declared all of the objects individually and created a static array of member pointers to the objects.

    Like so:

    struct obj
    {
        int somestuff;
        double someotherstuff;
    };
    
    class foo
    {
      public:
        obj apples;
        obj bananas;
        obj oranges;
    
        static obj foo::* fruit[3];
    
        void bar();
    };
    
    obj foo::* foo::fruit[3] = { &foo::apples, &foo::bananas, &foo::oranges };
    
    
    void foo::bar()
    {
        apples.somestuff = 0;
        (this->*(fruit[0])).somestuff = 5;
        if( apples.somestuff != 5 )
        {
            // fail!
        }
        else
        {
            // success!
        }
    }
    
    
    
    int main()
    {
        foo blee;
        blee.bar();
        return 0;
    }
    

    It seems to work for me. I hope that helps.

提交回复
热议问题