如何在C 中的二维数组中超载运算符[]
How to Overload operator[] for a Two-Dimmensional Array in C++
我有一个类 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背景现在可能很明显。谢谢大家!
相关文章:
- 如何在音频处理中使用超能力时间拉伸类
- 我的超类中的模板问题与结构定义
- 在具有 MPI 的超立方体中广播
- 在 c++ 中调用超构造函数之前做一些事情
- 我们可以在没有新实例化的情况下声明一个抽象方法来返回抽象超类中的子类对象吗
- C++为API中定义的结构创建超类
- 确保指向超类的指针指向c++中某个子类的对象
- 如何将超类的受保护成员访问到其派生类. 如果已在派生类中声明了具有相同名称的函数?
- C++:从类型索引中获取超类类型索引
- C++11 中对超载'ref(Select::Expressions::Code&)'的调用模棱两可
- 如何将项目放入具有模板化超类类型的向量中
- QT 中的串行通信超时与 Arduino
- 是否有一种方法可以在超载运算符函数中接触默认运算符函数
- 如何将基类方法超载作为参数传递到C 中的模板类
- Python C API-返回功能超载中的不同类型
- 编译器如何在超载中区分浮动和双重参数
- 此代码运算符超载中的错误是什么?
- 尝试在构造函数中超限时间
- 更改所有子类中超类变量的值
- 如何在C++中超类某些数据结构