C++ c+;中的成员变量因未知原因发生更改+;。。?

C++ c+;中的成员变量因未知原因发生更改+;。。?,c++,class,private-members,C++,Class,Private Members,我正在创建一个包含单元格的程序,为此我有一个Cell类和一个CellManager类。单元组织在二维数组中,单元类管理器有两个int成员变量xgrid和ygrid,它们反映了数组的大小 由于某种原因,我无法理解,这些成员变量在程序执行过程中会发生变化。有人能看到为什么会发生这种情况,或者告诉我该往哪里看 使用的类和函数如下所示: class Cell { public: Cell(int x, int y); } ----------------------------

我正在创建一个包含单元格的程序,为此我有一个Cell类和一个CellManager类。单元组织在二维数组中,单元类管理器有两个int成员变量xgrid和ygrid,它们反映了数组的大小

由于某种原因,我无法理解,这些成员变量在程序执行过程中会发生变化。有人能看到为什么会发生这种情况,或者告诉我该往哪里看

使用的类和函数如下所示:

class Cell
{
    public:
        Cell(int x, int y);
}

---------------------------------

class CellManager
{
     public:
         CellManager(int xg, int yg)

         void registercell(Cell* cell, int x, int y);
         int getxgrid() {return xgrid;}
         int getygrid() {return ygrid;}

     private:
         int xgrid;
         int ygrid;         
         Cell *cells[40][25];

}

-----------------------

and CellManagers functions:

CellManager::CellManager(int xg, int yg)
{
    CellManager::xgrid = xg;
    CellManager::ygrid = yg;
}

void CellManager::registercell(Cell *cell, int x, int y)
{
    cells[x][y] = cell;
}
以下是主要功能:

int main ()
{
    const int XGRID = 40;
    const int YGRID = 25;

    CellManager *CellsMgr = new CellManager(XGRID, YGRID);

    std::cout << CellsMgr->getxgrid() << std::endl; // PRINTS 40 
    std::cout << CellsMgr->getygrid() << std::endl; // PRINTS 25

    //create the cells and register them with CellManager
    for(int i = 1; i <= XGRID; i++) {

        for(int j = 1; j <= YGRID; j++) {

            Cell* cell = new Cell(i, j);
            CellsMgr->registercell(cell, i, j);
        }
    }

    std::cout << CellsMgr->getxgrid() << std::endl; // PRINTS A RANDOM LARGE INT, EX. 7763680 !!
    std::cout << CellsMgr->getygrid() << std::endl; // PRINTS 1, ALWAYS !!
int main()
{
常数int XGRID=40;
常数int YGRID=25;
CellManager*CellsMgr=新的CellManager(XGRID,YGRID);

std::cout getxgrid()数组是零索引的,但您使用它们时,就好像它们是从1索引的一样。因此,数组索引将覆盖单元格,并注销数组的结尾,这是一种未定义的行为。覆盖随机的其他变量当然是可能的。

您有一个明显的错误,它会损坏内存。
s/1/0/
s/所有指针都有什么用?如果您使用标准容器而不是指针数组和动态分配的对象,那么就不会出现堆损坏问题,代码也会更简单。您不应该像那样使用
new
并试图手动管理内存,事实证明代码不起作用k、 @chris,系统以后的大小会有所不同,所以我认为在堆上动态创建单元格最有意义,但我绝对不是专家..?在C++11
std::array
,或
std::vector
。任何按值存储
Cell
对象的东西,而不是指向堆对象的指针。甚至
单元格[40][25]
可能更好。啊,我明白了!非常感谢:)