将静态变量重置回 false
Resetting a static variable back to false
每分钟都有新的水果被推入流水线,每个水果都必须更新。 但只有香蕉会发出警告,指出存在太成熟的香蕉。此警告只能发出一次才能代表所有香蕉。 然后下一分钟,当新的水果涌入时,香蕉警告(如果有的话)必须再次发出。如何通过单独修改 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()
函数外部更新。
相关文章:
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- 伪造事实↔false
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- QueryWorkingSet总是返回false
- #为""定义宏;静态";针对不同的上下文
- cmake如何在fedora工作站中找到boost静态库包
- 静态数据成员的问题-修复链接错误会导致编译器错误
- 将公共但非静态的成员函数与ALGLIB集成
- cmake在我的项目中所需的所有静态库都不成功
- C++从另一个类访问公共静态向量的正确方法是什么
- 基于boost的程序的静态链接——zlib问题
- 在静态库中嵌入类方法
- Qt C++静态thread_local QNetworkAccessManager是线程应用程序的好选择吗
- 如何在C++中获得"静态纯虚拟"功能?
- 私有类型的静态常量成员
- 使用gcc从静态链接的文件中查找可选符号
- 在 .h 文件中的类中声明静态变量和在.cpp文件中声明"global"变量有什么区别
- 如何在C++中使用非静态成员函数作为回调函数
- 将静态库链接到不带-fPIC的共享库中
- 将静态变量重置回 false