类指针的 C++ 2D 数组

c++ 2d array of class pointers

本文关键字:2D 数组 C++ 指针      更新时间:2023-10-16

我正在尝试创建一个包含我类的指针的 2D 数组。 首先,我想将它们全部分配给 NULL:

Timetable::Timetable(int hours) : TimetableBase(hours){
    scheduledLectures = new Lecture**[5];
    for (int i = 0; i < 5; i++) {
        scheduledLectures[i] = new Lecture*[hours];
        for (int j = 0; j < hours; j++)
            scheduledLectures[i][j] = NULL;
    };
}

这适用于时间表生成器应用程序。 我有一个函数来设置这些指向特定对象的指针。

void Timetable::setLecture(Lecture& lecture){
    while ((lecture.getDuration()) -1 > 0){
        scheduledLectures[lecture.getDayScheduled()][(lecture.getHourScheduled())+1] = &lecture;
    }
}

编译器不会为此返回任何错误,但是当它运行时,指针似乎仍然是 NULL。我确定错误在 setter 函数内部(并且几乎可以肯定这是一个语法错误(,但我找不到解决方案。这是怎么回事?

谢谢

使用指针

shared_ptr s(或 unique_ptr s,具体取决于您的生命周期如何安排(的指针vector(或std::array(而不是您自己管理的 2D 指针数组。 省去手动管理对象的内存和生存期的麻烦。

class TimeTable {
    vector<vector<shared_ptr<Lecture>>> scheduledLectures;
};
Timetable::Timetable(int hours) 
        : TimetableBase(hours), 
        scheduledLectures(5, vector<shared_ptr<Lecture>>(5)) {}
void Timetable::setLecture(std::shared_ptr<Lecture> lecture){
    while ((lecture->getDuration()) -1 > 0) { // not sure what this does
        scheduledLectures[lecture->getDayScheduled()][(lecture->getHourScheduled())+1] = lecture;
    }
}

您可以测试shared_ptr是否为空,如下所示

auto s_ptr = std::shared_ptr<int>{}; // null
// either assign it to a value or keep it null
if (s_ptr) { 
    // not null
}

如果您在其他地方管理Lecture对象的内存,那么只需使用指针的 2D 向量并信任您的代码

class TimeTable {
    vector<vector<Lecture*>> scheduledLectures;
};
Timetable::Timetable(int hours) 
        : TimetableBase(hours), 
        scheduledLectures(5, vector<Lecture*>(5)) {}
void Timetable::setLecture(Lecture& lecture){
    while ((lecture.getDuration()) -1 > 0) { // not sure what this does
        scheduledLectures[lecture.getDayScheduled()][(lecture.getHourScheduled())+1] = &lecture;
    }
}