c++中未知原因的成员变量变化



我正在创建一个包含Cell的程序,为此我有一个Cell类和一个CellManager类。单元格被组织成二维数组,Cell类管理器有两个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 !!

所以,我初始化一个CellMgr,并通过构造函数设置xgrid和ygrid。然后我创建一堆单元格并将它们注册到CellMgr。在此之后,CellMgr的两个成员变量发生了变化,有人知道这是如何发生的吗?

数组是零索引的,但是您使用它们时就好像它们是从1开始索引的。因此,您的数组索引将覆盖单元格,并写掉数组的末尾,这是未定义的行为。覆盖其他随机变量当然是可能的。

最新更新