如何在C 中的二维数组中超载运算符[]

How to Overload operator[] for a Two-Dimmensional Array in C++

本文关键字:超载 中超 运算符 二维数组      更新时间:2023-10-16

我有一个类 MAP ,该使用vector<Cell>存储Cell s的二维数组。我超载 operator[]以访问 MAP 使用map[i][j]

我的问题是它仅适用于第一行数据。i = 1一旦得到细分故障。代码在下面,任何帮助都将不胜感激!谢谢

在地图类中(如果您需要更多详细信息,请让我知道)

/* Declaration of the vector<Cell> */
vector<Cell> map_;
/* The Operator Overload */
const Cell* operator[](int x) const {
    return &map_[x * this->width_];
}
/* Constructor */
explicit Map(double mapStep) : stepSize_(trunc(mapStep * 1000) / 1000) {
    if (mapStep > 0) {
        this->height_ = trunc((ARENA_HEIGHT / mapStep));
        this->width_ = trunc((ARENA_WIDTH / mapStep));
    } else { cerr << "Map Constructor Error #2" << endl; return; }
    mapInit();
}
void mapInit() {
    int i = 0, j = 0;
    this->map_.resize(this->height_ * this->width_);
    for (auto &cell : this->map_) {
        cell = Cell(Cell::cell_type::NOGO, i, j);
        if (j < this->width_ - 1) { j++; } else { j = 0; i++; }
    }
}

main()中的代码:

int i = 0, j = 0;
Map * map = new Map(20);
for (; i < map->getHeight() ;) {
    cout << "[" << map[i][j]->x << ", " << map[i][j]->y << ", " << map[i][j]->t << "]";
    if (j < map->getWidth() - 1) { j++; } else { j = 0; i++; cout << endl; }
}

输出

[0,0,255] [1,0,255] [2,0,255] [3,0,255] [4,0,255] [5,0,255] [6,255] [6,0,255] [7,0,255] [8,0,255] [9,0,255] [10,0,255] [11,0,255]分段故障

第一行输出似乎是正确的,并且使用operator()超载的先前测试工作正常,我真的需要使用[]。

我不知道为什么失败了,但是我能够通过遵循Paul的建议将Map * map = new Map(20);Map map(20);

来解决。

我的Java背景现在可能很明显。谢谢大家!