有关动态内存分配new的问题

问题遇到的现象和发生背景

想利用动态内存分配创建存储地图数据的一维数组,

问题相关代码,请勿粘贴截图

要求使用容器string

运行结果及报错内容

错误如下,求改正。

我的解答思路和尝试过的方法

img

我想要达到的结果

最后输出类似于这样
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0

22行,哪来的_size_x_变量啊,成员变量是size_x_啊。

删除size, _data数据成员

构造函数修改:
costmap_ = new unsigned char[size];

析构函数:
delete [] costmap_;

你的构造函数中,使用列表给成员变量赋值的方法你搞错了,样式应该是:
类名(变量1,变量2):成员变量1(变量1),成员变量2(变量2)
而且,你的成员变量名跟构造函数中的都不一致,还出现了不存在的成员变量。
_data不是数据类型,不能用new申请空间。

img

你的代码改成下面的:

#include <iostream>
#include <cstring>
#include <malloc.h>

using namespace std;
using std::ostream;

class Costmap2D
{
private:
    char name[20];
    unsigned int size_x_;
    unsigned int size_y_;
    double resolution_;
    unsigned char* costmap_;
    //下面两个注释掉,目前看来没有任何用处
    //unsigned char* size; 
    //unsigned char* _data;
public:
    Costmap2D(unsigned int size_x,unsigned int size_y,double resolution /*,unsigned int size*/)
        :size_x_(size_x),size_y_(size_y),costmap_(NULL),resolution_(resolution)
    {
        unsigned int size = size_x * size_y;
        costmap_ = new unsigned char[size];

        // create the comstom
        initMaps(size_x_,size_y_);
        resetMaps();
        
    }

    ~Costmap2D()
    {
        delete[] costmap_;
        costmap_ = 0;
    }
    //后面的函数自己补充
};