定义:
#include<iostream>
using namespace std;
// 结构体(类?)
// 允许储存不同的数据类型
struct student
{
string name;
int age;
int score;
};
// 或者直接定义对象
struct worker
{
string name;
int age;
int score;
}s3;
// 创建具体对象
int main()
{
struct student s1;
s1.name = "张三";
s1.age = 18;
s1.score = 100;
cout << "姓名: " << s1.name << " 年龄:" << s1.age << " 分数:" << s1.score << endl;
// 也可以
student s2{"李四",20,90};
cout << "姓名: " << s2.name << " 年龄:" << s2.age << " 分数:" << s2.score << endl;
s3.name = "王五";
s3.age = 26;
s3.score = 99;
cout << "姓名: " << s3.name << " 年龄:" << s3.age << " 分数:" << s3.score << endl;
}
结构体数组
#include<iostream>
using namespace std;
// 结构体数组
struct student
{
string name;
int age;
int score;
};
int main()
{
struct student arr[3]
{
{"张三", 18, 100},
{"李四",20,99},
{"王五",23,88}
};
for (int i=0;i<3;i++)
{
cout << "姓名:" << arr[i].name << " 年龄:" << arr[i].age << " 分数:" << arr[i].score << endl;
}
}