测试代码:
#include <iostream>
#include <Windows.h>
#include <string.h>
using namespace std;
class data
{
public:
DWORD first; // 四个字节
char * second;
char * combine;
public:
data();
void combineBoth(); // combineBoth()里面实现的是 combine = first + second 的数据。
void separateEither(); // separateEither()里面实现的是 first = combine(0~3), second = combine(4~n);
void displayAllData();
};
data::data(){
first = 9999;
second = new char[10];
combine = new char[14];
const char * temp = "123456789"; // 这里会有结束符
strcpy(second, temp);
}
void data::combineBoth(){
memcpy( (void*)combine, (void *) &first, 4);
memcpy( (void*)(combine+4), (void*)second, 10);
}
void data::separateEither(){
memcpy( (void *) &first, (void*)combine, 4);
memcpy( (void*)second, (void*)(combine+4), 10);
}
void data::displayAllData()
{ cout << "first:____" << first << endl;
cout << "second:____" << second << endl;
cout << "combine:____" << combine << endl;
}
int main(){
cout << "初始化\n";
data * myData = new data();
myData -> displayAllData();
cout << "\n合并\n";
myData -> combineBoth();
myData -> displayAllData();
cout << "\n分解\n";
myData->first = 0;
myData -> separateEither();
myData -> displayAllData();
system("pause");
return 0;
}
运行结果:
初始化
first:____9999
second:____123456789
combine:____屯屯屯屯屯屯屯铪铪铪
合并
first:____9999
second:____123456789
combine:____'
分解
first:____9999
second:____123456789
combine:____'
请按任意键继续. . .
这样是不是成功了?
有什么方法可以看见combine内存下每一个字节的内容呢?