2017-08-15 56 views
0

當調用buildingname.damagebuilding(34)時,當前健康狀況只會暫時降低,第一次打印會打印100第二次打印66,但是在再次調用damagebuilding之後,它會再次重置爲100。 currenthealth不是在其他地方設置的,而是在構造函數中。C++類函數無法更改變量

類:

class building { 
public: 
    int maxhealth; 
    int currenthealth; 
    int cost; 
    int level; 
    int Posx; 
    int Posy; 
    building() {} 
    building(int h, int c, int x, int y) { 
     maxhealth = h; 
     currenthealth = h; 
     cost = c; 
     level = 1; 
     Posx = x; 
     Posy = y; 
    } 

    void damageBuilding(int h) { 
     if (currenthealth - h > 0) { 
      std::cout << " Before "+std::to_string(currenthealth); 
      currenthealth=currenthealth-h; 
      std::cout << "\n After " + std::to_string(currenthealth)+"\n"; 
     } 
     else { 
      std::cout << "\n Building destroyed "; 
     } 
    } 

}; 

當它被稱爲:

void fire(int x,int y) { 
    if (activeplayer == 1 && bulletsP1 > 0 && sgrid2[x][y] != 0) { 
     if (sgrid2[x][y] > 0 && sgrid2[x][y] < 9) { 
      for (std::list<cannon>::iterator it = cannonsP1.begin(); it != cannonsP1.end(); ++it) { 
       if (it->ID == bulletsP1) { 
        findbuilding(x, y).damageBuilding(it->damage); 
       } 
      } 
     } 
     bulletsP1--; 
     sgrid2[x][y] = grid2[x][y]; 
     vgrid2[x][y] = 3; 
    } 
} 

Findbuilding:

building & findbuilding(int x, int y) { 
    if (activeplayer == 1) { 

     for each (building b in bgrid2) 
     { 
      if (b.Posx == x && b.Posy == y) { 
       return b; 
      } 
     } 

    } 
    //else if (activeplayer == 2) { 
    else { 
     for each (building b in bgrid) 
     { 
      if (b.Posx == x && b.Posy == y) { 
       return b; 
      } 
     } 
    } 
} 
+0

[關話題]你在'的std ::法院使用to_string'的'<< 「之前」 + std :: to_string(currenthealth);'不需要,代價高昂。你可以在<< currenthealth;之前使用'std :: cout <<「,現在你沒有動態內存分配或者額外的拷貝。 – NathanOliver

+2

'findbuilding(x,y)'返回什麼?希望這是一個參考。 – drescherjm

+0

@drescherjm位於x,y的建築物 –

回答

0

功能

findbuilding(x, y) 

按值返回類building的實例,這意味着您只修改實例的副本。您必須返回pointer(*)或reference(&)才能生效。


building findbuilding(int x, int y) {} 

building & findbuilding(int x, int y) {} 

還有就是你用currenthealth = 100內存

+-----+-----+-----+-----+-----+ 
|  |  | i |  |  | 
|  |  | 100 |  |  | 
+-----+-----+-----+-----+-----+ 

如果按價值copy返回它的實例i,這種細胞是警察滅蠅燈在內存中另一個地方,iCpy

+-----+-----+-----+-----+------+ 
|  |  | i |  | iCpy | 
|  |  | 100 |  | 66 | 
+-----+-----+-----+-----+------+ 
      ^  ^
       |   --------------- You are modifying this copy 
       --------------------------- The real instance stays unchanged 

傳遞一個引用到這個實例

+-----+-----+-----+-----+-----+ 
|  |  | i |  |  | 
|  |  | 66 |  |  | 
+-----+-----+-----+-----+-----+ 
      ^   
       -------------------------- You are modifying real instance 
+0

謝謝,但它並沒有解決它,讓我對事情變得更加困惑,例如,每當我再次運行時,將當前的健康狀況改爲看似隨機的數字。 –

+0

正如我在評論中提到的,您的問題是_method無法改變變量_,現在你可以看到成員變量在方法中被成功修改了,問題就在函數'damageBuilding'中。一步一步調試,你會看到什麼問題。不那麼難。 :-) –

+0

好的!我會盡力而爲,閱讀所有的回覆讓我感覺我的代碼比我想象的要多得多。感謝您的幫助! –