目录
一、结构体定义及使用
如:定义一个学生数据结构体类型,包括 姓名、年龄、分数
首先,定义结构体时的语法:struct 结构体名 { 结构体成员列表 };
struct Student{ string name;int age = 0;int score = 0;};
定义结构体时,struct关键字不能省略
其次,通过结构体定义结构体变量的方法有3种:
1、struct 结构体名 变量名;
struct Student s1;
2、struct 结构体名 变量名 = { 成员1,成员2... };
struct Student s2 = { 成员1,成员2...};
有些版本使用第二种方法可能会报错
前两种方法,定义结构体变量时,struct关键字可以省略
3、在定义结构体时,创建结构体变量
struct Student{ string name; int age = 0; int score = 0;}s3;
#include <iostream>
using namespace std;
struct Student
{
string name;
int age = 0;//这里如果不赋初值,有些版本会出现警告
int score = 0;
}s3;//3、定义结构体时顺便创建变量
int main()
{
//1、struct 结构体名 变量名;
struct Student s1;
s1.name = "张三";// 用 . 来访问结构体变量中的属性
s1.age = 10; //输入 . 后,会有提示,可以快捷选择想要赋值的属性
s1.score = 79;
cout <<"姓名:" << s1.name <<" 年龄:" << s1.age <<" 分数:" << s1.score << endl;
//2、struct 结构体名 变量名 = {成员1,成员2...};
struct Student s2 = {"李四",11,90};//顺序一定是按照定义结构体时的顺序
cout <<"姓名:" << s2.name <<" 年龄:" << s2.age <<" 分数:" << s2.score << endl;
//3、定义结构体时顺便创建变量
s3.name = "王五";
s3.age = 12;
s3.score = 100;
cout <<"姓名:" << s3.name <<" 年龄:" << s3.age <<" 分数:" << s3.score << endl;
system("pause");
return 0;
}