C++Note 结构体数组 结构体嵌套结构体
结构体数组:成员变量访问是通过 . 结构体数组的指针 实现的是指向 为 ->
1 #include <iostream> 2 using namespace std; 3 //结构体数组 4 //1.定义结构体 5 struct Student 6 { 7 //成员列表 8 string name; //姓名 9 int age; //年龄 10 }; 11 int main() 12 { 13 //2.创建结构体数组 14 //3.给结构体数组的元素赋值 15 //4.遍历结构体数组 16 Student stuArray[3] = 17 { 18 {"s1", 10}, 19 {"s2", 20}, 20 {"s3", 30} 21 }; 22 for (int i = 0; i < 3; i++) 23 { 24 cout << "姓名: " << stuArray[i].name << " 年龄: " << stuArray[i].age << endl; 25 } 26 system("pause"); 27 return 0; 28 }
结构体指针:
1 #include <iostream> 2 using namespace std; 3 //结构体数组 4 //1.定义结构体 5 struct Student 6 { 7 //成员列表 8 string name; //姓名 9 int age; //年龄 10 }; 11 int main() 12 { 13 //2.创建结构体变量 14 Student s1 = { "s1", 10 }; 15 //3.通过指针指向结构体变量 16 Student* p = &s1; 17 //4.通过指针访问结构体变量中的数据 18 cout << "姓名: " << p->name << " 年龄: " << p->age << endl; 19 system("pause"); 20 return 0; 21 } 22 //通过结构体指针 访问结构体中的属性 需要利用 '->'
结构体嵌套结构体:
1 #include <iostream> 2 using namespace std; 3 //结构体嵌套结构体 4 struct Student//1.定义结构体 5 { 6 //成员列表 7 string name; //姓名 8 int age; //年龄 9 }; 10 struct Teacher 11 { 12 int id; 13 string name; 14 Student stu1; 15 Student stu2; 16 }; 17 int main() 18 { 19 Teacher t1; 20 t1.id = 101; 21 t1.name = "t1"; 22 //结构体老师参数 23 t1.stu1.name = "s1"; 24 t1.stu1.age = 1; 25 //结构体老师中结构体学生stu1实例参数 26 t1.stu2.name = "s2"; 27 t1.stu2.age = 2; 28 //结构体老师中结构体学生stu2实例参数 29 system("pause"); 30 return 0; 31 }
 
                    
                 
                
            
         
 浙公网安备 33010602011771号
浙公网安备 33010602011771号