结构体
用户自定义的数据类型,类似于class
创建学生类,先打开vi搜死丢丢
创建结构体和创建对象
struct Student {//自定义的数据类型:数据类型的集合 string name; int age; int score; }s3; int main() { //创建Student对象 //1. struct Student s1; s1.name = "张三"; s1.age = 18; s1.score = 100; cout << "姓名:" << s1.name << endl; cout << "年龄:" << s1.age << endl; cout << "分数:" << s1.score << endl; //2. struct Student s2 = { "李四",19,80 }; cout << "姓名:" << s2.name << endl; cout << "年龄:" << s2.age << endl; cout << "分数:" << s2.score << endl; //3.结构体的大括号后面,分号之前直接创建对象 s3.name = "王二麻子"; s3.age = 100; s3.score = 10; cout << "姓名:" << s3.name << endl; cout << "年龄:" << s3.age << endl; cout << "分数:" << s3.score << endl; system("pause"); return 0; }
结构体数组
Student arrays[3] = { {"张三",20,100}, {"李四",21,80}, {"王五",30,60} }; for (int i = 0; i < sizeof(arrays) / sizeof(arrays[0]); i++) { cout <<"姓名:"<< arrays[i].name << " "; cout <<"年龄:"<< arrays[i].age << " "; cout <<"分数:"<< arrays[i].score << " "; cout << endl; } cout<< arrays[2].name<<endl;
结构体指针
//结构体指针:通过指针访问结构体中的成员 //利用操作符->访问 Student stu1 = { "张三",20,100 }; Student* p = &stu1; cout << p->name << endl;//指针访问 cout << (*p).name << endl;
结构体嵌套结构体
#include"methodState.h" struct Student {//自定义的数据类型:数据类型的集合 string name; int age; int score; }; struct Teacher { int id; string name; int age; Student stu1; Student stu2; }; int main() { //结构体嵌套 Student stu1 = { "张三",20,100 }; Teacher t1 = { 2021,"李四",33,stu1 }; cout << t1.stu1.name << endl; t1.stu2.name = "王五"; t1.stu2.age = 19; t1.stu2.score = 75; system("pause"); return 0; }
结构体做函数参数
#include"methodState.h" struct Student {//自定义的数据类型:数据类型的集合 string name; int age; int score; }; void printStudent(Student stu) { cout << "值传递:" << stu.name << endl; cout << "值传递:" << stu.age << endl; cout << "值传递:" << stu.score << endl; } void printStudent(Student* stu) { cout << "地址传递:" << stu->name << endl; cout << "地址传递:" << stu->age << endl; cout << "地址传递:" << stu->score << endl; } int main() { Student stu1 = { "张三",20,100 }; printStudent(stu1); printStudent(&stu1); system("pause"); return 0; }
P68一半
来源:b站黑马