我正在尝试使 attiny 闪烁 LED 模拟蜡烛。我对 C++ 知之甚少。
我有一个名为 CandleAnimation
的类,它是根据对控制 LED 的对象的引用构造的。我想构造一个 Candle
对象来维持模拟蜡烛的状态。
运行循环调用 CandleAnimation
上的 animate
方法。我不确定这里到底发生了什么,但看起来我的 Candle
超出了范围并且正在被销毁。
#include "candle_animation.h"
CandleAnimation::CandleAnimation(Led *led, Color flameColor) {
_led = led;
Candle candle(_led, 0xFF0000);
_candle = &candle;
_candle->play(); // shows red as expected
delay(500); // this prevents the run loop from starting so I have to delete this code to get the animate to work
}
void CandleAnimation::animate(int sliderValue, int ambientBrightness) {
Candle otherCandle(_led, 0x00FF00);
otherCandle.play(); // shows green as expected
delay(500); // this stops the following code from being random actually. instead it's a dim green on the LED
_candle->play(); // shows grazy things . . . seemingly random
}
那么,如何使用指向对象的指针初始化我的实例并保留该对象以便我可以在其他成员方法中使用它?
最佳答案
如果你想在你的类中保留一个合适的蜡烛对象,请在标题中使用它:
Led* _led;
Candle _candle;
在这种情况下,构造函数变为:
CandleAnimation::CandleAnimation(Led *led, Color flameColor)
: _led(led)
, _candle(led, 0xFF0000)
{
// Rest of the constructor
}
如果你想保持动态分配(你不想),将 _candle
声明为 unique_ptr
:
std::unique_ptr<Candle > _candle ;
然后(如果你有 C++14):
_candle = std::make_unique(_led, 0xFF0000);
在 C++11 中:
_candle = std::unique_ptr(new Candle(_led, 0xFF0000));
如果您没有现代 C++(不确定 arduino 提供了什么?),您需要做同样的事情,但要跟踪 _candle
生命周期。
关于c++ - 在构造函数中初始化私有(private)成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53819340/