這段代碼如何,它是標準的嗎?我已經在Visual C++頭文件中看到過這種代碼,它可以計算某些結構成員的偏移量,但它是如何工作的?無需實例化計算結構構件的偏移
#include <iostream>
struct Foo
{
int a;
int b;
int c;
};
int main(int argc, char** argv)
{
int* i1 = (&((Foo*)0)->a);
int* i2 = (&((Foo*)0)->b);
int* i3 = (&((Foo*)0)->c);
std::cout << "i1 = " << i1 << "\ni2 = " << i2 << "\ni3 = " << i3 << "\n";
return 0;
}
Results : i1 = 0, i2 = 4, i3 = 8
編輯: 只記得我之前看過這個代碼的地方。它在WinNT.h
#define FIELD_OFFSET(type, field) ((LONG)(LONG_PTR)&(((type *)0)->field))
在''中定義了一個標準的宏'offsetof(structure,field)',正是這樣做的。所以是的,代碼是有效的,但使用標準宏將使其更加標準。 –
DyZ
TL; DR:實現可以做這樣的事情,你不能。 –
我不能做什麼,我可以做到,我的程序有效。 – nikau6