Kon*_*tin 0 c++ arrays pointers destructor dynamic-memory-allocation
所以这是一个关于动态内存分配和对象创建的C++练习.基本上 - 一个自定义类学生和一个自定义类组,它保留了一系列指向学生内部的指针.Group的析构函数显然存在问题,但我花了几个小时阅读手册和浏览论坛,但仍然无法理解我做错了什么.
欢迎任何评论.
UPD:问题是 - 退出时出错."调试断言失败了...... _BLOCK_TYPE_IS_VALID ......"
class Student{
char *firstName;
char *lastName;
public:
Student(): firstName(NULL), lastName(NULL){}
Student(const char *fname, const char *lname){
firstName = new char[32];
lastName = new char[32];
strcpy_s(firstName, 32, fname);
strcpy_s(lastName, 32, lname);
}
void Show(){
cout << firstName << " " << lastName << endl;
}
~Student(){
if(lastName != NULL)
delete[] lastName;
if(firstName != NULL)
delete[] firstName;
}
};
class Group{
Student *students;
int studentCounter;
public:
Group(){
students = NULL;
}
Group(const int size){
students = new Student[size];
studentCounter = 0;
}
void Push(Student *student){
students[studentCounter] = *student;
studentCounter++;
}
void ShowAll(){
for(int i = 0; i < studentCounter; i++){
students[i].Show();
}
}
~Group(){
if(students != NULL)
delete[] students; //problem here?
}
};
void main(){
Student jane("Jane", "Doe");
Student john("John", "Smith");
Group group(2);
group.Push(&jane);
group.Push(&john);
group.ShowAll();
_getch();
}
Run Code Online (Sandbox Code Playgroud)