C语言日记 30 联合体类型

书P113:

联合体类型变量声明的语法形式是:

<联合体类型名><联合体变量名>;

联合体类型变量的引用形式是:

<联合体变量名>,<成员名>.

例如:

a=18;

C='A';

x=51.8;

不是你这举的例子和前面的内容他这也不搭啊???

你他m到底想表达什么东西?

例7-3

联合体的应用。

源程序:

#include 
using namespace std;
struct example
{
	char id[10];
	char name[20];
	char sex;
	int age;
	union
	{
		float salary;
		float score;
	};
}teacher, student;
void main()
{
	example teacher = { "000788","WangWei",'M',30,5000 };
	example student = { "000518","ZhangYu",'F',20,95 };
	cout << teacher.id << "   " << teacher.name << "   " << teacher.sex
		<< "   " << teacher.age << "   " << teacher.salary << endl;
	cout << student.id << "   " << student.name << "   "
		<< student.sex << "   " << student.age << "   "
		<< student.score << endl;
	cout << "sizeofstudent = " << sizeof(student) << endl;
	cout << "sizeofteacher = " << sizeof(teacher) << endl;
}

结果:

而这里,我们可以通过实践发现,如果我们

把“老师的薪水”和“学生的分数”变量类型互换变为“老师的分数”和“学生的薪水”:

#include 
using namespace std;
struct example
{
	char id[10];
	char name[20];
	char sex;
	int age;
	union
	{
		float salary;
		float score;
	};
}teacher, student;
void main()
{
	example teacher = { "000788","WangWei",'M',30,5000 };
	example student = { "000518","ZhangYu",'F',20,95 };
	cout << teacher.id << "   " << teacher.name << "   " << teacher.sex
		<< "   " << teacher.age << "   " << teacher.score << endl;
	cout << student.id << "   " << student.name << "   "
		<< student.sex << "   " << student.age << "   "
		<< student.salary << endl;
	cout << "size of student = " << sizeof(student) << endl;
	cout << "size of teacher = " << sizeof(teacher) << endl;
}

具体改动的地方:

    cout << teacher.id << "   " << teacher.name << "   " << teacher.sex
        << "   " << teacher.age << "   " << teacher.score << endl;
    cout << student.id << "   " << student.name << "   "
        << student.sex << "   " << student.age << "   "
        << student.salary << endl;

不仅程序运行没问题(可以输出),而且该动前后输出的结果还一模一样

你可能感兴趣的:(C++,c语言,c++,开发语言,1024程序员节)