在构造函数中初始化私有成员

时间:2018-12-17 16:32:10

标签: c++ arduino

我正在尝试使模拟蜡烛的LED出现一点点闪烁。我对C ++知之甚少。

我有一个名为CandleAnimation的类,该类是通过引用控制LED的对象来构造的。我想构造一个Candle对象,该对象保持模拟蜡烛的状态。

运行循环在animate上调用CandleAnimation方法。我不太确定这里到底发生了什么,但是我的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
}

那么,如何使用指向对象的指针初始化实例并保持该对象周围,以便可以在其他成员方法中使用它?

2 个答案:

答案 0 :(得分:2)

如果您想在班级中保留适当的蜡烛对象,请在标题中使用此对象:

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的生命周期。

答案 1 :(得分:1)

CandleAnimation::CandleAnimation(Led *led, Color flameColor)
    : _candle(new Candle(led, 0xFF0000)) // this is making you sure that your candle will be valid until being deleted
{
  _led = led;

  //  Candle candle(_led, 0xFF0000); this is a local variable and will be deleted after constructor execution. You don't need it anymore
  //  _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
}
// don't forget to delete _candle in destructor