【发布时间】:2021-03-25 18:09:14
【问题描述】:
我想制作许多“学生”类型的对象并将它们存储起来,以便在整个程序中使用它们。我还需要在创建和销毁学生时打印出消息,但是当我将“已销毁”消息放入析构函数时,每当我更改实例以创建下一个学生时,它就会出现,因为调用了析构函数。有没有办法绕过它,只在我的程序结束时为每个对象调用析构函数?
每当要创建下一个学生(每个 for 循环)时,当前的这段代码都会销毁每个学生,然后在程序结束时再次“重新销毁”。我只希望它们在最后被删除。
#include <iostream>
#include <string>
class Student{
// members
public:
Student(){}
Student(std::string name, int floor, int classroom ){
std::cout<<"Student created\n\n";
// assignments
}
~Student(){std::cout<<"Student destroyed\n\n";}
// methods
};
int main(int argc, char** argv) {
Student* S=new Student[5];
for (int i=0; i<5; i++){
S[i]=Student("example", 1,1); //makes 5 students and stores them
}
// rest of the program
delete[] S;
return 0;
}
【问题讨论】:
-
你认为为什么每个学生都在循环中被摧毁?您将它们存储在一个数组中。
-
-
S[i]=Student("example", 1,1);创建一个Student类型的临时对象,使用参数"example"、1和1进行初始化,分配S[i]成为一个copy 临时的,并销毁临时的。 -
此外,在标准 C++(自 1998 年以来)中,最好避免(直接)使用运算符
new和delete- 在担心调用析构函数的频率之前先尝试学习如何做到这一点.在很多情况下,它可以更轻松地避免不必要的对象构造和破坏。 -
将赋值运算符代码添加到您的类并在调用时打印。
标签: c++ oop object destructor