之前我们学习了基础类型的 C++动态数组
现在我们来看动态数组的元素是类对象的场景
对象数组
对象数组的每一个元素都是一个类对象。
#include <iostream>
#include <string>
struct Student
{
std::string name;
int age;
};
void InitStudentArray(Student* stu, int totalStudent)
{
for (int i = 0; i < totalStudent; ++i)
{
stu[i].name = "student_name" + std::to_string(i);
stu[i].age = 0;
}
}
void PrintAllStudents(Student* stu, int totalStudent)
{
for (int i = 0; i < totalStudent; ++i)
{
std::cout << stu[i].name << ", " << stu[i].age << std::endl;
}
}
int main(void)
{
int totalStudent = 10;
Student* stuArray = new Student[totalStudent];
InitStudentArray(stuArray, totalStudent);
PrintAllStudents(stuArray, totalStudent);
delete[] stuArray;
return 0;
}
程序输出如下: