在对象中构造 int 后从对象递增 int C++

Incrementing an int from an object after it's constructed in C++

本文关键字:对象 int C++      更新时间:2023-10-16

我有一个游戏,每个转弯都会创建一个新的兔子对象。每个兔子都有一个年龄的年龄,我希望游戏中每个对象的每个传球都会增加年龄。
我为逐渐增加年龄的班级制作了一种方法,但似乎只会增加一次。
我如何继续?

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;
}

这里的主要问题似乎是您在最内向的 for循环中处理兔子向量的副本。当您写作:

for (auto e : bunnies)
{
    // More code here
}

e只是该位置的向量中的任何元素的副本,而不是原始元素本身。

如果您想修改向量中的元素,请通过参考访问它们,并相应地调用其突变器。例如:

for (auto & e : bunnies)
//        ^
// Note the ampersand above.
{
    int tempAge = e.get_age();
    e.agePlusOne(); // Now this will change the internal state
                    // of `age` for this bunny.
    // More code
}

这将修改实际对象,而不仅仅是复制。