acr*_*uui 0 c++ class private-members
我正在创建一个包含Cells的程序,为此我有一个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;
}
Run Code Online (Sandbox Code Playgroud)
这是主要功能:
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 !!
Run Code Online (Sandbox Code Playgroud)
因此,我初始化一个CellMgr,并通过构造函数设置xgrid和ygrid.然后我创建了一堆Cells并将其注册到CellMgr.在此之后,CellMgr的两个成员变量发生了变化,有谁知道这会发生什么?