【问题标题】:Incrementing an int from an object after it's constructed in C++在 C++ 中构造对象后从对象递增 int
【发布时间】: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))。你所做的只是操纵副本。

标签: c++ class int


【解决方案1】:

这里的主要问题看起来是您在最里面的for 循环中处理兔子向量的副本。当你写:

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

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

如果您想修改向量中的元素,请通过 reference 访问它们并相应地调用它们的 mutator。例如:

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
}

这将修改 实际 对象,而不仅仅是一个副本。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-22
    • 2020-05-24
    • 2019-09-12
    • 2010-10-25
    • 1970-01-01
    • 1970-01-01
    • 2014-10-24
    相关资源
    最近更新 更多