base.h:
class Base{
public:
explicit Base();
uint32_t _val1, _val2, _val3;
uint8_t _val4, _val5;
uint32_t _val6;
uint8_t _val7, _val8;
uint32_t _val9, _val10, _val11;
uint8_t _valA;
uint8_t _valB;
uint8_t _valC;
};
base.cpp:
Base::Base(){
_valA = 0xAA;
_valB = 0xBB;
_valC = 0xCC;
printf("Base: _valA addr=%p val=%x\n", &_valA, _valA);
printf("Base: _valB addr=%p val=%x\n", &_valB, _valB);
printf("Base: _valC addr=%p val=%x\n", &_valC, _valC);
}
der.h:
class Der : public Base
{
public:
explicit Der();
uint32_t _der1;
uint32_t _der2;
uint32_t _der3;
};
der.cpp:
#pragma pack (1)
#include "der.h"
Der::Der()
: Base()
{
printf("Der: _valA addr=%p val=%x\n", &_valA, _valA);
printf("Der: _valB addr=%p val=%x\n", &_valB, _valB);
printf("Der: _valC addr=%p val=%x\n", &_valC, _valC);
printf("Der: _der1 addr=%p val=%08x\n", &_der1, _der1);
printf("Der: _der2 addr=%p val=%08x\n", &_der2, _der2);
printf("Der: _der3 addr=%p val=%08x\n", &_der3, _der3);
fflush(stdout);
}
main.cpp中:
int main(){
Der *pder = new Der();
return 0;
}
我使用" #pragma pack(1)"时的输出在der.cpp:
Base: _valA addr=0x80048304 val=aa
Base: _valB addr=0x80048305 val=bb
Base: _valC addr=0x80048306 val=cc
Der: _valA addr=0x80048300 val=0
Der: _valB addr=0x80048301 val=0
Der: _valC addr=0x80048302 val=0
Der: _der1 addr=0x80048303 val=ccbbaa00
Der: _der2 addr=0x80048307 val=00000000
Der: _der3 addr=0x8004830b val=00000000
我们可以看到值的地址_valA,_valB和_valC在基类和派生类中是不同的。此外,当我们在基类中更改_valA,_valB或_valC的值时,将更改_der1的值。当我从der.cpp中删除#pragma时,一切正常。我在MSVC2010,GCC4.9.1和clang 3.4.2(windows平台)上测试了这段代码。有人可以解释一下为什么会出现这个问题吗?