我有:
class Foo {
int a;
int b;
std::string s;
char d;
};现在,我想知道给定Foo*时a,b,s,d的偏移量
例如,假设我有:
Foo *foo = new Foo();
(char*) foo->b == (char*) foo + ?? ; // what expression should I put in ?发布于 2010-03-12 16:04:36
我不知道为什么你想要一个成员的偏移量到你的struct,但是偏移量是允许在给定结构地址的情况下获得指向成员的指针的东西。(请注意,标准的offsetof宏只适用于POD-structs (您的不适用),因此这里不是一个合适的答案。)
如果这就是你想要做的,我建议使用指向成员的指针,因为这是一种更可移植的技术。例如:
int main()
{
int Foo::* pm = &Foo::b;
// Pointer to Foo somewhere else in the program
extern Foo* f;
int* p = &(f->*pm);
}请注意,这只在b在Foo中不是私有的情况下才有效,或者您也可以在成员函数或Foo的朋友中形成指向成员的指针。
https://stackoverflow.com/questions/2430954
复制相似问题