简体   繁体   中英

C++ Pointer to struct member

If I were to make a struct, say:

struct FOO{    
    int x, y, z, a, b, c;  
}

int main(){  
    FOO foo = {1, 2, 3, 4, 5, 6};        

    return 0;
}

Would there be anyway to create a pointer that can access FOO's integer members?
Maybe by making pointer that points to foo and then somehow modifying it to increment in integers?

I know that if I were to make FOO a class instead with a method that returns a pointer to the first int, then I could cycle though the members with ++ or [i](in a for loop). But I want to know if I can access structure members simply by knowing the address of the struct (assuming I have a good understanding of how to navigate said struct)

Any insight would be much appreciated. Thanks!

You can overload operator[] for the struct:

struct bar // ALL_UPPERCASE is for macros!
{
    int a, b, c, d, e, f;
    int operator[](size_t i) const
    {
        switch(i)
        {
        case 0: return a;
        case 1: return b;
        case 2: return c;
        case 3: return d;
        case 4: return e;
        case 5: return f;
        default: assert(false);
        }
    }
};

Just a thought and this might not work, but you could try doing a pointer to the foo struct and then shifting the pointer by the size of an int for each element. So something like:

    int * ptr= & foo;
    ptr++;

If I'm remembering my hardware design class well enough a struct is actually really similar to an array in memory it can just have variable sized blocks of memory for each of its indices.

struct FOO{    
    int x, y, z, a, b, c;  
} __attribute__ ((packed))

FOO foo;
int *i = &foo;

In this case, the attribute ((packed)) eliminates the problem created by padding, since it get's rid of it. Afterwards incrementing i, grantees that it will be in the next element of the struct.

It's pretty straightforward:

Foo foo = { 1, 2, 3, 4, 5, 6 };
int* pfoo = &foo.x;

int structMembers = sizeof(Foo) / sizeof(int);
for (int i = 0; i < structMembers; i++)
{
    cout << pfoo[i] << endl;
}

There's no difference between a struct and class aside from default access modifier (private in structs, public in classes). Thus whatever you can do with classes, you can do with structs.

As I understood you need this: https://en.cppreference.com/w/cpp/utility/functional/mem_fn

if you need own implementation take this:

#include <iostream>

struct Foo
{
  int a = 1;
  char b = 'a';
};

template<typename Struct, typename var_type>
const var_type member_get( Struct& obj, var_type Struct::* mem_var ) { return 
obj.*mem_var; }

int main() 
{
  Foo x;
  std::cout << member_get( x, &Foo::a ) << std::endl;
  std::cout << member_get( x, &Foo::b ) << std::endl;
  return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM