//
// Created by 徐昌真 on 2024/10/5.
//
#include <iostream>
#include <cstring>
using namespace std;
//定义一个结构体(类)
struct Info{
char _name[20];
int _role; //老师是0 同学是1
union { //用union存放score和course 节省内存
int score;
char course[20];
}_sc; //创建一个_sc union对象
//构造一个函数用于传入数据 (构造函数名与类名(构造名)相同)
Info(const char name[20], int role, int s, const char c[20]) {
strcpy_s(_name, name); //交换将name赋予给_name
_role = role;
if(role > 0){
_sc.score = s;
}else if(role == 0){
strcpy_s(_sc.course, c);
}
}
};
int main() {
Info a[2] = { //调用函数 并且创建一个数组用于多次向函数里面传参
Info("徐昌真",1,100,""),
Info("徐老师",0,-1,"python"),
};
for (int i = 0; i < 2; ++i){
if(a[i]._role == 1){
cout << a[i]._name << "的成绩是:" << a[i]._sc.score << endl;
}else{
cout << a[i]._name << "教的是" << a[i]._sc.course << endl;
}
}
return 0;
}
输出结果