我有:
class Foo {
int a;
int b;
std::string s;
char d;
};
Run Code Online (Sandbox Code Playgroud)
现在,我想知道给定Foo*的a,b,s,d的偏移量
也就是说我有:
Foo *foo = new Foo();
(char*) foo->b == (char*) foo + ?? ; // what expression should I put in ?
Run Code Online (Sandbox Code Playgroud)
我不知道为什么你想要一个成员的偏移到你的struct,但偏移是允许在给定结构的地址的情况下获得指向成员的指针.(请注意,标准offsetof宏仅适用于POD结构(不属于您),所以这里的答案不合适.)
如果这是你想要做的,我会建议使用指向成员的指针,因为这是一种更便携的技术.例如
int main()
{
int Foo::* pm = &Foo::b;
// Pointer to Foo somewhere else in the program
extern Foo* f;
int* p = &(f->*pm);
}
Run Code Online (Sandbox Code Playgroud)
请注意,这仅在b非私有的情况下才有效Foo,或者您可以在成员函数或朋友中形成指向成员的指针Foo.