c++ - 在 C++ 中增加自定义对象数组的大小

标签 c++ arrays

我有一个学生类和动态创建的学生数组:

class Student{
public:
  void create(){
    system("cls");
    cout << "First name: ";
    cin >> fn;
    cout << "Last name: ";
    cin >> ln;
    cout << "How many subjects? ";
    cin >> sub_number;
    subjects = new string[sub_number];
    for(int i = 0; i < sub_number; i++){
      cout << "Subject name: ";
      cin >> subject[i];
    }
  }

  //This just display the student with a bunch of couts
  friend ostream& operator<<(ostream&, const Student&);

  ~Student(){ delete[] subjects; }
private:
  string fn;
  string ln;
  string* subjects;
  int sub_number;
};

我需要将这个数组的大小增加 1,并向其中添加一个新学生。

当我尝试简单地做到这一点时:

void main(){
   int stu_number = 0;
   cout << "How many students? "
   cin >> stu_number;
   Student* students = new Student[stu_number];

   //creating/updating initial students using user input
   for(int i = 0; i < stu_number; i++){
     students[i].create();
   }

   //displaying all students
   for(int i = 0; i < stu_number; i++){
     cout << students[i];
   }

   //trying to add a student
   add_new_student(students, stu_number);

   //displaying all students again
   for(int i = 0; i < stu_number; i++){
     cout << students[i];
   }
}

add_new_student 函数:

void add_new_student(Student* students, int& stu_number){
  Student* temp = new Student[stu_number++];
  for (int i = 0; i < stu_number - 1; i++){
    temp[i] = students[i];
  }
  temp[stu_number - 1].create(); 
  delete[] students;
  students = temp;
}

我收到内存冲突错误和未处理的异常:add_new_student 函数内的访问冲突写入位置 0xABABABAB。

  • 这样做的正确方法是什么?
  • Student 类是否缺少一些重要的组件?

我不能使用 std::vectorstd::list 因为这是学校作业:)

最佳答案

要增加数组的大小,您基本上必须:

  • 创建一个更大的新数组
  • 将值从旧的较小数组复制到新的较大数组
  • 删除旧的较小数组

话虽如此,如果您可以,我建议您切换到 std::vector,因为它具有可以为您调整大小的实用方法。

关于c++ - 在 C++ 中增加自定义对象数组的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29257052/

相关文章:

c - 指针和数组—艰苦学习C

c++ - 为什么 switch 和 if 语句与转换运算符的行为不同?

C++ : how to read a char file in a fast way into a char array?

c++ - 指针和 `const` 的 C/C++ 约定

c# - 如何在 C# 中映射双 C 结构指针?

c++ - 在 C++ 中实例化类的所有不同方法是什么?

c++ - std::array 复制语义

ios - Swift .insert 在数据库条目中

java - 尝试使用嵌套循环获取非重复数字..(二维数组)

java - 重写 findResource