C++ union 和struct的使用

来源:互联网 发布:php 执行git命令 编辑:程序博客网 时间:2024/06/07 09:21
#include <iostream>
#include <cstring>
using namespace std;
struct Person
{long num;
char name[10];
char sex;
char job[10];
union
{int class_;
char position[11];
} category;
};
void printStudent(Person student);
void printTeacher(Person teacher);
int main()
{
    Person student1={01,"xiaoming",'M',"student",1};
    cout<<"the person information:";
    printStudent(student1);
 Person    teacher1={02,"xiaohong",'F',"teacher"};//注意共同体只能对第一个元素初始化,即class_   Person    teacher1={02,"xiaohong",'F',"teacher","cuhehueh"};是报错的//省略元素初始化,只会初始化前几个
 
  strcpy(teacher1.category.position,"math teacher");//设置职称为math_teacher

    cout<<"the person information:";
     printTeacher(teacher1);
    

    return 0;
}
void printStudent(Person student)
{
    cout<<endl;
    cout<<"num="<<student.num<<"\t";
    cout<<"name="<<student.name<<"\t";
    cout<<"sex="<<student.sex<<"\t";
    cout<<"job="<<student.job<<"\t";
    cout<<"class="<<student.category.class_<<"\t"<<endl;
}
void printTeacher(Person teacher)
{
    cout<<endl;
    cout<<"num="<<teacher.num<<"\t";
    cout<<"name="<<teacher.name<<"\t";
    cout<<"sex="<<teacher.sex<<"\t";
    cout<<"job="<<teacher.job<<"\t";

    cout<<"position="<<teacher.category.position<<"\t"<<endl;

cout<<" i like qianzicong"<<endl;

}

0 0
原创粉丝点击