【发布时间】:2016-06-21 14:23:48
【问题描述】:
我有一个游戏,每回合它都会创建一个新的 Bunny 对象。每只兔子都有一个年龄,我希望游戏中每个对象的年龄每经过一个回合就增加一次。
我为该类创建了一个增加年龄的方法,但它似乎只增加一次。
我该如何进行?
class Bunny
{
private:
std::string sex, color, name;
int age;
public:
void agePlusOne(void);
Bunny();
~Bunny();
};
void Bunny::agePlusOne()
{
age += 1; // Or age++;
}
int main()
{
int the_time;
clock_t startTime = clock(); //Start timer
clock_t testTime;
clock_t timePassed;
double secondsPassed;
std::vector<Bunny> bunnies; //Bunny objects container
while (true)
{
testTime = clock();
timePassed = startTime - testTime;
secondsPassed = timePassed / (double)CLOCKS_PER_SEC;
the_time = (int)secondsPassed * -1;
if (the_time % 2 == 0) //This is what happens each turn
{
for (auto e : bunnies)
{
e.agePlusOne(); //All bunnies age one year
}
bunnies.push_back(Bunny()); //Adds bunny object to vector
}
}
//End of program
system("pause");
return 0;
}
【问题讨论】:
-
为什么是指针!?
age++;还不够好吗? -
它在这个过于简单的情况下做了一些事情。所以我向您保证,问题在于您没有向我们展示的代码。我猜有些东西被遮住了。
-
如果它只增加一次,那么你只调用它一次。
-
你获取年龄(
int tempAge = e.get_age();),增加内部年龄(e.agePlusOne();),然后检查年龄(if(tempAge == 2))。你所做的只是操纵副本。