3

我遇到了一个非常奇怪的错误,在我离开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

}

有谁知道可能出了什么问题?

4

2 回答 2

4
CTile me = this->tiles[curLine][curCol];

那应该是

CTile& me = this->tiles[curLine][curCol];
me.setType(1);

为什么?因为您制作了 CTile 的副本,而不是创建对二维数组中的那个的引用。您现在可能会发现崩溃已移至me.setType(1)语句。

于 2011-05-06T16:22:43.710 回答
4
CTile  me = this->tiles[curLine][curCol];

这是问题所在。 me是 原始对象的副本tiles[curLine][curCol],因此您所做的任何事情me都不会反映在原始对象中。即使您这样做,原始对象也保持不变me.setType(1)。我敢肯定你不想那样。

所以解决方法是:使用参考:

CTile & me = this->tiles[curLine][curCol];
  //  ^ note this
me.setType(1);

或者更好的是,您可以简单地这样做:

tiles[curLine][curCol].setType(1); //"this" is implicit!
于 2011-05-06T16:23:26.857 回答