第二章 C++结构体
语法:struct 结构体名 { 结构体成员列表 };
通过结构体创建变量的方式有三种:
//.cpp #include "structuralMessage.h" #include <iostream> #include <string> template<typename T, size_t N> char(&ArraySizeHelper(const T(&array)[N]))[N]; #define ARRAY_SIZE(array) (sizeof(ArraySizeHelper(array))) using namespace std; struct Teacher{ string code; string type; }teacher; void structuralDefinition(){ student s1={"张三",20,100000}; student s2; s2.age=300; s2.name="金丹修士"; s2.score=1; putMessage(s1); putMessage(s2); teacher.code="鸿蒙老祖"; teacher.type="修仙"; cout<<teacher.type<<"\t"<<teacher.code<<endl; } void putMessage(student stuL){ cout<<"姓名:"<<stuL.name<<"\t年龄:"<<stuL.age<<"\t英语成绩:"<<stuL.score<<endl; }
//.h #include <string> using namespace std; struct student{ string name; int age; int score; }; class structuralMessage { }; void structuralDefinition(); void putMessage(student stuL);
struct 结构体名 数组名[元素个数] = { {} , {} , … {} }
student arr[]={ {"李逍遥",24,12}, {"灵儿",23,120}, {"茂茂",26,1} }; //auto可以在声明变量的时候根据变量初始值的类型自动为此变量选择匹配的类型,类似的关键字还有decltype。 for (auto & i : arr) { cout << "姓名:" << i.name << " \t年龄:" << i.age << " \t分数:" << i.score << endl; }
可以通过定义一个结构体指针指向这个结构体的一个对象。
利用操作符 ->
可以通过结构体指针访问结构体属性。
//结构体指针 void structPointer(){ student stu={"张三",20,100000}; //定义结构体指针 student *p=&stu; cout<<p->name<<endl; }
结构体中的成员可以是另一个结构体。
struct student{ string name; int age; int score; }; struct Teacher{ string code; string type; struct student stu; }; //结构体嵌套结构体 void structNesting(){ Teacher ToNi[]={ {"球球","炼丹",{"小孟",14,58}}, {"冷萌","炼器",{"萧炎",12,80}}, {"球球","炼丹",{"小花",13,57}}, }; for(auto &i:ToNi){ if(i.code=="球球") { cout << "教师 职工姓名: " << i.code << " \t教授科目: " << i.type << endl; cout << "辅导学员 姓名: " << i.stu.name << " \t年龄:" << i.stu.age << " \t考试分数: " << i.stu.score << endl; } } }
传递方式有两种:
//如果不想修改主函数中的数据,用值传递,反之用地址传递 void putMessage(student stuL){ cout << "姓名:" << stuL.name << "\t年龄:" << stuL.age << "\t英语成绩:" << stuL.score << endl; } void putMessageTwo(student *stuL){ stuL->score=100; cout<<"姓名:"<<stuL->name<<"\t年龄:"<<stuL->age<<"\t英语成绩:"<<stuL->score<<endl; }