c++ - 在构造函数中初始化私有(private)成员

标签 c++ arduino

我正在尝试使 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/

相关文章:

arduino - 我怎样才能将arduino pin设置为跳线?

c - Arduino 的串行监视器输入?

c++ - 打包一个 HTML5 应用并将其部署在桌面上

c++ - 在预编译头文件中实例化模板会减少编译时间吗?

python - 如何在 Python 中将两个字节的整数转换回整数?

c++ - 使用单个 memset 清零多个数组/假设允许内存布局?

c - 不知道分配 float ,整数是否正确加倍

C++ 如何格式化指向类数组的指针?

c++ - 如何在单个 vector 中存储不同的类?

c++ - 创建静态包含 ffmpeg 的共享库