自定义对象构造函数在循环外部循环
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
构造函数中,创建ItemType
对象输入大小的new
数组。此数组的元素将在构建数组时默认构造。这就是为什么您的Student
构造函数被称为数组乘以的大小。
相关文章:
- CMake 外部和内部静态库的循环依赖关系
- 全局变量的循环依赖性与外部说明符
- 自定义对象构造函数在循环外部循环
- C++:在循环内部或外部声明一个向量
- 在主循环外部多个文件上定义全局变量
- C++嵌套循环,外部有变量
- 如何在 for 循环内部或外部打印双精度变量
- C++:外部对象循环引用
- 与外部循环具有相同变量名称的内部循环
- 针对外部标志(cpp)的循环条件的更改
- 为什么用于解析我读取的行的内部循环每隔一次迭代就会通过外部读取循环跳过
- 用于循环通过未知大小的外部普通数组
- 在循环内声明变量,但在外部使用它
- 编译器省略外部循环
- 如何在没有外部标志的情况下只在循环中运行一次代码
- Apache Thrift外部事件循环
- 带有一个外部指针的链接节点的循环链
- 在对象外部循环遍历unique_ptr集合
- 如何调用外部c函数,而GLUT显示循环锁定了我的c++主函数
- OpenMP -嵌套for循环在外部循环之前并行时变得更快.为什么