我遇到了一个非常奇怪的错误,在我离开 for
范围后,我无法访问我的指针在循环期间指向的任何内容,即使在类中声明了包含对象的数组标题。
这是代码的基础:
Class CTile{/*代码*/};
Class CMap
{
public:
CTile** tiles;
CMap();
}
CMap::CMap()
{
int lines = 10;
int cols = 10;
tiles = new CTile*[lines];
for(int i = 0 ; i (lower than) lines;++)
{
this->tiles[i] = new CTile[cols];
}
for(int curLine = 0; curLine (lower than) lines ; curLine++)
for(int curCol = 0; curCol (lower than) cols; curCol++)
{
CTile me = this->tiles[curLine][curCol];
me.setType(1);
//do whatever I need, and inside the loop everything works.
}
int a = this->tiles[2][2].getType(); // a gets a really weird number
this->tiles[2][2].setType(10); // crashes the program
}
有谁知道哪里出了问题?
最佳答案
CTile me = this->tiles[curLine][curCol];
应该是
CTile& me = this->tiles[curLine][curCol];
me.setType(1);
为什么?因为您复制了 CTile,而不是在二维数组中创建对 CTile 的引用。您现在可能会发现崩溃已转移到 me.setType(1)
语句。
关于C++在范围结束后丢失指针引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5914196/