第2个回答 2013-04-02
// 2013-04-02-001.cpp : 定义控制台应用程序的入口点。//
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
typedef struct test
{
string strname;
int nid;
int age;
char sex[10];
unsigned int sn: 4;
} test_a,test_b[2];
typedef struct test2
{
string strname;
int nid;
int age;
char sex[5];
unsigned int sn: 4;
} test_a2;
union best
{
int number;
char name[10];
double value;
}pbest;
int _tmain(int argc, _TCHAR* argv[])
{
test_a *ptest=new test_a;
ptest->strname="中国人";
ptest->nid=300;
cout<<"test_a.name= "<<ptest->strname<<"\n"<<"test_a.nid= "<<ptest->nid<<endl;
test test_b[2]={
{"wj",18,30,"man"},
{"jack",28,40,"woman",88},
};
//test2 testa2={"kfc",28,40,"woman",88};
test2 testa2;
testa2.strname="kfc";
testa2.age=28;
testa2.nid=40;
strcpy(testa2.sex,"woman");//值超出数组范围
testa2.sn=2231;
cout<<"test_b.name= "<<test_b[0].strname<<endl;
cout<<"testa2.name= "<<testa2.strname<<endl;
cout<<"testa2.sex= "<<testa2.sex<<endl;
cout<<"testa2.sn= "<<testa2.sn<<endl;
pbest.number=30;//分别赋值
cout<<"pbest.number= "<<pbest.number<<endl;//分别输出
pbest.value=800;
cout<<"pbest.value= "<<pbest.value<<endl;
strcpy(pbest.name,"新中国");
cout<<"pbest.name= "<<pbest.name<<endl;
//best pbest={50,800,strcpy(pbest.name,"新中国")};
system("pause");
return 0;
}
这样输出的原因:结构体里面的每一个元素都占有一定的内存空间。而共用体占用其元素中最长的变量的那个类型的内存空间。其赋值是覆盖式的