我正在研究如何在C++中将成员的内存偏移量转换为类,并在维基百科上看到了这一点:
在C++代码中,您不能使用offsetof来访问非Plain Data Data Structures的结构或类的成员.
我尝试了它似乎工作正常.
class Foo
{
private:
int z;
int func() {cout << "this is just filler" << endl; return 0;}
public:
int x;
int y;
Foo* f;
bool returnTrue() { return false; }
};
int main()
{
cout << offsetof(Foo, x) << " " << offsetof(Foo, y) << " " << offsetof(Foo, f);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我收到了一些警告,但它已经编译,运行时它给出了合理的输出:
Laptop:test alex$ ./test
4 8 12
Run Code Online (Sandbox Code Playgroud)
我想我要么误解POD数据结构是什么,要么我错过了其他一些难题.我不知道问题是什么.