当该对象被动态分配时,是否可以安全地假设某个对象的字段按照其定义的顺序总是?
对我有用的例子:
struct Rectangle
{
int len;
int wid;
};
Rectangle* myRect = new Rectangle;
void* vPtr = myRect;
*(int*)(vPtr)
总是等同于myRect->len
和*(int*)(vPtr + sizeof(int))
等同于myRect->wid
吗?
这种情况也会发生同样的事吗?
class Button
{
Rectangle* frame;
Char* Text;
} *myButton;
void * vButton = myButton;
*(int*)((*Rectangle)(vButton))
是len
字段吗?
因为我不想要一本大书作为答案我会问下面的问题。 当我有更多这样的课程时:
#define WND_BUTTON 1
#define WND_EDIT 2
class Button
{
private:
BYTE TypeWindow;
SMALL_RECT srFrame;
*Some other fields*
public:
Button();
*Just functions here*
}
class Edit
{
private:
BYTE TypeWindow;
SMALL_RECT srFrame;
/*Some other fields*/
public:
Edit();
/*Just functions here*/
}
typedef void* HANDLE;
我能依靠这张支票吗?
HANDLE hWindow = Create(...);
if (*(BYTE*)(hWindow) == WND_BUTTON)
std::cout<<"This is a button."<<std:endl;
if (*(BYTE*)(hWindow) == WND_EDIT)
std::cout<<"This is a text field."<<std:endl;