我刚开始使用 C++,但我一直在解决一个非常烦人的问题。一旦我使用动态数组,我就被卡住了。数组在调试中看起来真的很乱(看图片),一旦我将更多的一个对象添加到数组中,它就会崩溃。这不是我得到一个特定项目的错误,而是所有使用动态数组的代码,我什至尝试编译老师在本课程中编写的代码,但没有成功。因此,问题不太可能是代码,但可能是其他问题。但是,为了安全起见,我确实包含了我用来证明这一点的测试代码。
#include "iostream"
#include "string"
#include "Student.h"
int main()
{
_CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
string input;
Student **students = NULL;
students = new Student*[20];
for(int i = 0; i < 20; i++)
{
students[i] = new Student();
}
for(int i = 0; i < 20; i++)
{
delete students[i];
}
delete[] students;
return 0;
}
#include "Student.h"
#include "string"
Student::Student()
{
name = "";
number = 0;
}
Student::Student(string Name)
{
name = Name;
number = 0;
}
Student::~Student()
{
}
string Student::getName() const
{
return name;
}
#ifndef STUDENT_H
#define STUDENT_H
#include "string"
#include "Course.h"
using namespace std;
class Student
{
private:
string name;
int number;
public:
Student();
Student(string Name);
virtual ~Student();
string getName() const;
};
#endif