C++作用域结束后丢失指针引用
我遇到一个非常奇怪的错误,在离开 for
范围后,即使在类头中声明了保存对象的数组,我也无法访问循环期间指针指向的任何内容。
这是代码的基本内容:
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
}
有谁知道可能出了什么问题?
I'm getting a really weird error where after I leave the for
scope I can't access whatever my pointer was pointing during the loop even if the array holding the objects is declared in the class header.
This is the basic of the code:
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
}
Does anyone know what could be wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
那应该是
为什么?因为您制作了 CTile 的副本,而不是创建对二维数组中的引用。您现在可能会发现崩溃已转移到
me.setType(1)
语句。That should be
Why? Because you made a copy of CTile, instead of creating a reference to the one in the 2-dimensional array. You might now discover that the crash has moved to the
me.setType(1)
statement.问题就在这里。
me
是原始对象tiles[curLine][curCol]
的副本,因此无论您对me
做什么 code> 未反映在原始对象中。即使您执行me.setType(1)
,原始对象也保持不变。我确信你不希望这样。所以解决方法是:使用引用作为:
或者更好的是,你可以简单地这样做:
Here is the problem.
me
is a copy of the original objecttiles[curLine][curCol]
, so whatever you're doing withme
isn't reflected in the original object. The orginal object remains unchanged even if you dome.setType(1)
. I'm sure you didn't want that.So the fix is : use reference as :
Or better yet, you can simply do this: