更改对象中一个变量的值会更改所有其他类似对象变量

时间:2014-11-21 11:14:41

标签: c++ pointers object

不是最好的头衔,所以我会改变以更好地解释自己。我目前正在学习c ++,并决定尝试A * Path Finding。它找到路径没有问题,但是当为FreeTile设置父牌时,它将所有其他FreeTile的父牌设置为相同。因此,当我展示所有父母时,他们也表现出相同的一切。

Tiles作为基类Tile存储在数组中,然后使用引用转换为FreeTile并转换回指针。 (不确定这是不是很糟糕)。

导致此问题的具体代码如下:

currentTile是指向...当前磁贴的指针,它是从数组映射中的指针引用转换而来的。

setParent只是更改对象中的父指针。

currentTile->setParent(tile);
currentTile->setF(calculateF(currentTile));
open.push_back(currentTile);

整个部分是:

try{
    Tile* currentTileF = mapp[i+y][j+x];
    Tile& currentRef = *currentTileF;
    //cout<<"Trying to convert from Tile to FreeTile"<<endl;
    FreeTile& currentFRef = dynamic_cast<FreeTile&>(currentRef);
    currentTile = &currentFRef;
    free = true;
 }catch(bad_cast& bc){
    //cout<<"Bad Cast: "<<bc.what()<<endl;
    currentTileClosed = static_cast<ClosedTile*>(mapp[i+y][j+x]);
    free = false;
 }
 if(free){
     if(currentTile->getFree() && !inCloseList(currentTile)){
         if(!inOpenList(currentTile)){
             currentTile->setParent(tile);
             currentTile->setF(calculateF(currentTile));
             open.push_back(currentTile);
         }else{
             //cout<<"Already in open list"<<endl;
             if(currentTile->getCoordX()==tile->getCoordX() || currentTile->getCoordY()==tile->getCoordY()){
                 if((tile->getG() +10) < currentTile->getG()){
                     currentTile->setParent(tile);
                     currentTile->setF(calculateF(currentTile));
                     //cout<<"Updated Parent and F value for Horiz: "<<currentTile<<endl;
                 }
             }else{
                 if((tile->getG() +14) < currentTile->getG()){
                     currentTile->setParent(tile);
                     currentTile->setF(calculateF(currentTile));
                     //cout<<"Updated Parent and F value for Diag: "<<currentTile<<endl;
                 }
             }
         }
     }else{
         //cout<<"Either not free or in close list"<<endl;
 }

如果我没有解释任何明显不幸的事情,请尝试更好地解释:P

而且作为c ++的新手,并且在编写A * PF之前从未对其进行编码,因此任何建议通常都会得到很好的回复:)

由于

编辑:

我做的测试代码:

try{
    FreeTile& tempRef = dynamic_cast<FreeTile&>(*mapp[3][4]);
    FreeTile& tempRefP = dynamic_cast<FreeTile&>(*mapp[1][2]);
    FreeTile* temp = &tempRef;
    FreeTile* tempP = &tempRefP;
    temp->setParent(tempP);
}catch(bad_cast& bc){
}

这会立刻改变所有父母,虽然它只是为了改变mapp [3] [4]的父母

0 个答案:

没有答案