范围结束后C ++丢失了指针引用
|
我收到一个非常奇怪的错误,在离开“ 0”作用域后,即使在类头中声明了包含对象的数组,也无法访问循环期间指针指向的内容。
这是代码的基础:
Class CTile{ /*Code*/ };
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
}
有谁知道可能是错的吗?
没有找到相关结果
已邀请:
2 个回复
厘恼轨
那应该是
为什么?因为您制作了CTile副本,所以没有在二维数组中创建对该副本的引用。您现在可能会发现崩溃已移至the5ѭ语句。
逆捐凶撤小
这是问题所在。
是原始对象
的副本,因此您对
所做的任何操作都不会反映在原始对象中。即使您执行
,原始对象仍保持不变。我确定您不想要那样。 因此,解决方法是:将引用用作:
或者更好的是,您可以执行以下操作: