c++ - 成员变量在 C++ 中因未知原因而更改..?

标签 c++ class private-members

<分区>

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

出于某种原因我无法弄清楚,这些成员变量在程序执行过程中会发生变化。任何人都可以看到为什么会发生这种情况,或者可以指出我应该寻找的方向。

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

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。然后我创建了一堆 Cell 并将它们注册到 CellMgr。之后,CellMgr的两个成员变量发生了变化,谁知道这是怎么发生的?

最佳答案

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

关于c++ - 成员变量在 C++ 中因未知原因而更改..?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14093011/

相关文章:

c++ - 2D Box Collision - 这是对的吗?

python - 对象不匹配

java - 如何从给定类 Item 获取数组?

javascript - Ajax Javascript 类未定义

java - 使用反射访问大型 POJO 的私有(private)字段 : ±1?

c++ - 为什么编译器不提示 catch 子句?

不将 "inline"或 "static"关键字与无类函数一起使用时出现 C++ 重新定义链接错误

c++ - 为什么使用 Visual Studio 和命令行编译时大小不同

c++ - std::unique_ptr 作为参数的正确复制语义

javascript - MooTools 1.3+ 类中的私有(private)属性