c++ - C ++:根据变量将相同的对象实例化为多种类型之一
问题描述
我正在对我设计的 LED Cube 进行编程。立方体有一个“暂停”按钮和一个“播放/下一步”按钮。除非立方体暂停,否则它将循环播放我为它制作的所有不同效果(动画)。如果按下暂停按钮,立方体将不再在效果之间转换,而是重复当前效果。按下“播放/下一个”按钮将取消暂停功能并立即进入下一个效果。
其中一些效果非常复杂,需要在动画帧之间保留大量变量。为了立即轻松地销毁所有这些变量(例如按下下一个按钮时),我将当前动画实例化为一个对象,并在效果完成或按下跳过按钮时将其销毁。
我正在尝试按如下方式设置我的主循环:
void loop() {
//create an effect object
switch(effectIndex){
case 0:
EF_GROWFRAME effect;
break;
case 1:
EF_RANDOMFILL effect;
break;
}
bool proceed;
do{
//returns false until the effect has completed
proceed=effect.step();
//push this cube update and wait for it to display
cube.update();
cube.waitForFrame();
}
while ((!proceed)&&(!skipflag));
//skipflag is set true during a timer interrupt if the skip button is freshly pressed
skipflag=false;
cube.clearPattern();
if (play) effectIndex++;
if (effectIndex=effectCount) effectIndex=0;
}
这失败了,因为我对effect
虽然的定义相互矛盾。您可能会看到我要做什么,那么解决此问题的正确方法是什么?
解决方案
这是多态性的一个用例。
定义一个基类,Animation
它定义一个共享接口并让您的各种动画类型从中派生。例如:
class Animation {
public:
virtual ~Animation() {
// any generic cleanup shared by all animation types
}
virtual bool step() = 0;
};
class AnimationA : public Animation {
public:
bool step() override {
// logic for this type of animation
}
};
class AnimationB : public Animation {
public:
bool step() override {
// logic for this type of animation
}
};
void loop() {
std::unique_ptr<Animation> effect;
switch (effectIndex) {
case 0:
effect = std::make_unique<AnimationA>();
break;
case 1:
effect = std::make_unique<AnimationB>();
break;
}
//...
}
由于这似乎是一个嵌入式环境,您可以通过将动画播放逻辑分解到一个单独的函数中来避免我的第一个示例中的动态内存分配:
void playAnimation(Animation& effect) {
bool proceed;
do{
//returns false until the effect has completed
proceed=effect.step();
//push this cube update and wait for it to display
cube.update();
cube.waitForFrame();
} while (!proceed && !skipFlag);
//skipflag is set true during a timer interrupt if the skip button is freshly pressed
skipflag=false;
cube.clearPattern();
}
void loop() {
switch (effectIndex) {
case 0:
{
AnimationA effect;
playAnimation(effect);
break;
}
case 1:
{
AnimationB effect;
playAnimation(effect);
break;
}
}
if (play) effectIndex++;
if (effectIndex == effectCount) effectIndex=0;
}
推荐阅读
- laravel - 如何在laravel中将dompdf大小调整为身份证大小
- angular - NullInjectorError:StaticInjectorError[[object Object]]
- node.js - Node.js - 无法填写模块“大写”
- django - 如何定义 django 视图的权限?
- c# - c#中的必需参数错误
- javascript - javascript函数执行时加载屏幕
- python-3.x - 如何将来自“从模板 A 到模板 B”的模板 B 中的变量硬编码传递给路由函数?
- php - Laravel Eloquent 通过数据透视表加入
- python-3.x - 如何在 Mac 上升级 pip?
- authentication - Xamarin Forms WebView,如果在 webView 中对站点进行身份验证,则注册到 FCM 通知