執行後Goomba::liveGoombas
等於一些負值。我放棄了它,但不明白爲什麼它會多次構造函數啓動析構函數。爲什麼在這裏工作不正確?爲什麼靜態數據成員在發送到函數時更新不正確?
// Here is a simple Goomba class. It just keeps track of how many Goombas are alive.
class Goomba
{
public:
static int liveGoombas;
Goomba() { liveGoombas++; }
~Goomba() { liveGoombas--; }
};
int Goomba::liveGoombas = 0;
// And a Goomba legion class. Please don't change this class.
class GoombaLegion
{
public:
void add(Goomba goomba)
{
goombas.push_back(goomba); //it seems that something wrong in this function
}
private:
std::vector<Goomba> goombas;
};
void goombas()
{
{
GoombaLegion legion;
}
// The legion went out of scope and was destroyed. But how many Goombas are alive?
std::cout << "There are " << Goomba::liveGoombas << " live goombas" << std::endl;
}
int main()
{
goombas();
}
當我編譯並運行它,我看到有0直播goombas。我有點困惑,因爲你寫的東西出了問題,但你永遠不叫GoombaLegion ::增加。 –