#include <string>
#include <iostream>
struct test
{
int iID;
int iType;
std::string strName;
int iLevel;
test()
{
iID = 2;
iType = 2;
iLevel = 2;
strName = "Hello, world";
}
};
void Output(test& stTest)
{
char * pID = (char*)(&stTest);
cout << (int)(*pID) << endl;
cout << (int)(*(pID+sizeof(int))) << endl;
std::string *pName = (std::string *)(pID+sizeof(int) + sizeof(int));
cout << *pName << endl;
*pName = "hello";
cout << (int)(*(pID+sizeof(int) + sizeof(int)+sizeof(std::string))) << endl;
}
int main()
{
test stTest;
cout << sizeof(stTest) << endl;
Output(stTest);
Output(stTest);
}
结果如下:
40
2
2
Hello, world
2
2
2
hello
2
通过实验标明,string在结构体中只占用 sizeof(std::string)个字节,不会因为其中的内容长短而有所变化,
可见其中的内容是另一块存储区,本地只保存一个地址作为索引。