自定义对象构造函数在循环外循环

Custom object constructor is looping outside of a loop

出于某种原因,当我在我的代码中创建一个 Student 对象时,构造函数被输入了很多次,我不确定为什么。我在构造函数和下面的代码中放置了一个 cout 语句。任何关于为什么会发生这种情况的帮助都会很棒。

//Student.cpp
Student::Student() {
  ID = 0;
  name = "name";
  cout << "student constructor" << endl;
}

Student::Student(int id, string name) {
  ID = id;
  name = this->name;
  cout << "student con 2" << endl;
}




//part of SortedList.cpp just incase it is needed
template <class ItemType>
SortedList<ItemType>::SortedList() {
  cout << "In the default constructor" << endl;
  Max_Items = 50;
  info = new ItemType[Max_Items];
  length = 0;

//SortedList(50);//Using a default value of 50 if no value is specified                                                                                                              

}

//Constructor with a parameter given                                                                                                                                                 

template <class ItemType>
SortedList<ItemType>::SortedList(int n) {
  cout << "in the non default constructor" << endl;
  Max_Items = n;
  info = new ItemType[Max_Items];
  length = 0;
  cout << "At the end of the non default constructor" << endl;
}






 /The part of the driver where this is called
ifstream inFile;
  ofstream outFile;
  int ID; //what /below                                                                                                                                                              
  string name; //these werent here                                                                                                                                                   
  inFile.open("studcommands.txt");
  outFile.open("outFile.txt");
  cout << "Before reading commands" << endl;
  inFile >> command; // read commands from a text file                                                                                                                               
  cout << "After reading a command" << endl;
  SortedList<Student> list;//() was-is here                                                                                                                                          
  cout << "List has been made" << endl;
  Student StudentObj;
  cout << "Starting while loop" << endl;
  while(command != "Quit") {...}

//稍后我也遇到了分段错误核心转储。

更新 由于某种原因,无论我列出的列表有多长,我的学生构造函数都被输入了很多次,这意味着我输入 30 作为我列表中的长度,构造函数被输入 30 倍,而不是仅仅创建一个有 30 个槽的数组。这可能是什么原因?感觉以前好像听说过这个问题

SortedList 构造函数中,您创建一个 new 数组,其输入大小为 ItemType 个对象。该数组的元素将在构建数组时默认构造。这就是为什么您的 Student 构造函数被称为数组大小的原因。