将静态变量重置回 false

Resetting a static variable back to false

本文关键字:false 静态 变量      更新时间:2023-10-16

每分钟都有新的水果被推入流水线,每个水果都必须更新。 但只有香蕉会发出警告,指出存在太成熟的香蕉。此警告只能发出一次才能代表所有香蕉。 然后下一分钟,当新的水果涌入时,香蕉警告(如果有的话)必须再次发出。如何通过单独修改 Banana::update() 来完成这项工作? 所以没有全局变量来监视这一点,没有特殊的组装线成员函数来只检查香蕉(因为有很多类型的水果,我不希望在main()中调用香蕉的特殊函数)。 事实上,除了 Banana::update() 之外,除了 Banana 或 Fruit 中的一个辅助函数之外,什么都没有。

#include <iostream>
#include <list>
#include <array>
#include <cstdlib>
#include <ctime>
struct AssemblyLine {
    std::array<std::list<struct Fruit*>, 3> fruits;
    void createFruits();
    void updateAllFruits();
} myAssemblyLine;
struct Fruit {
    AssemblyLine& assemblyLine = myAssemblyLine;
    int ripeness = std::rand() % 10;
    virtual void update() = 0;
};
struct Apple : Fruit { virtual void update() override {} };
struct Orange : Fruit { virtual void update() override {} };
struct Banana : Fruit { virtual void update() override; };
void AssemblyLine::createFruits() {
    for (int i = 0; i < 20; i++) {
        fruits[0].push_back (new Apple);
        fruits[1].push_back (new Orange);
        fruits[2].push_back (new Banana);
    }
}
void AssemblyLine::updateAllFruits() {
    for (const auto& list : fruits)
        for (Fruit* f : list)
            f->update();
}
void Banana::update() {
    // This banana must be updated, but now check which banana is the most ripe.
    static bool alreadyWarned = false;
    int maxRipeness = 0;
    for (auto x : assemblyLine.fruits[2])
        if (x->ripeness > maxRipeness) maxRipeness = x->ripeness;
    if (!alreadyWarned && maxRipeness > 7) {
        std::cout << "Warning!  There is a banana that is too ripe!n";
        alreadyWarned = true;  // I want this warning to be stated at most once per minute.
    }
    // How to know when to reset alreadyWarned back to false?
}
int main() {
    std::srand(std::time(nullptr));
    for (int i = 0;  i < 5;  i++) {  // Each loop is a new minute, and I want the banana warning (if any) each minute.
        myAssemblyLine.createFruits();
        myAssemblyLine.updateAllFruits();
    }
    // Problem:  The banana warning is only issued in the first loop.
}

也许有比使用已经警告的静态变量更好的方法来编写 Banana::update() ?

您应该将函数作用域static bool alreadyWarned移动到class Banana作用域。 也就是说,使其成为静态成员变量。 从技术上讲,这不是全局的,但它与全局一样有用,因为它可以从update()函数外部更新。