0

私は新しく C++ を使い始めましたが、かなり厄介な問題に悩まされ続けています。動的配列を使用するとすぐに行き詰まります。配列はデバッグで本当に混乱しているように見え (画像を見てください)、さらに 1 つのオブジェクトを配列に追加するとすぐにクラッシュします。これは特定のプロジェクトを取得したエラーではありませんが、動的配列を使用するすべてのコードです。このコースで教師が作成したコードをコンパイルしようとしましたが、成功しませんでした。したがって、問題がコードである可能性は低く、おそらく別の何かです。ただし、安全のために、これを実証するために使用したテスト コードを含めました。 コードのデバッグ

#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
4

1 に答える 1

1

デバッガーで混乱しているように見える理由は、配列studentsではなく、学生(まだ割り当てられていないため、内容が適切に無効になっている)を表示しようとしているためです。デバッガーは、動的に割り当てられた配列を表示できません。

また、students = new Student();? これはコンパイルさえすべきではなく、ロジックは間違っていません。を に割り当てていStudent*ますStudent**

原則として、new[]独自のコードでは絶対に使用しないでください。常に使用しますstd::vector。次に、正しい数のクラスを自動的に構築し、Studentメモリリークやそのようなことは決してありません。

int main() {
    std::vector<Student> students;
    string input;
    students.resize(20);
    // Now you can use ALL THE STUDENTS
    return 0;
}
于 2012-05-10T16:21:25.430 に答える