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

Custom object constructor is looping outside of a loop

本文关键字:循环 外部 构造函数 对象 自定义      更新时间:2023-10-16

出于某种原因,当我在代码中创建 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构造函数中,创建ItemType对象输入大小的new数组。此数组的元素将在构建数组时默认构造。这就是为什么您的Student构造函数被称为数组乘以的大小。