當調用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;
}
}
}
}
[關話題]你在'的std ::法院使用to_string'的'<< 「之前」 + std :: to_string(currenthealth);'不需要,代價高昂。你可以在<< currenthealth;之前使用'std :: cout <<「,現在你沒有動態內存分配或者額外的拷貝。 – NathanOliver
'findbuilding(x,y)'返回什麼?希望這是一個參考。 – drescherjm
@drescherjm位於x,y的建築物 –