【问题标题】:error: use of 'this' in a constant expression in Arduino Class错误:在 Arduino 类的常量表达式中使用“this”
【发布时间】:2020-02-03 14:09:09
【问题描述】:

我正在尝试为 arduino 项目编写一个类,我使用 http://paulmurraycbr.github.io/ArduinoTheOOWay.html 中的信息作为指导。

我想设置一个灯带以供进一步使用,并不断收到错误消息:错误:在常量表达式中使用“this”。

我的代码如下所示:

#include <FastLED.h>

#define LED_STRIP_PIN 2
#define LED_STRIP_NUM_LEDS 10

//const unsigned char LED_STRIP_PIN = 2;
//const int LED_STRIP_NUM_LEDS = 10;

CRGB leds[LED_STRIP_NUM_LEDS];

class LedStrip {
  unsigned char  pin;

  public:
    LedStrip(unsigned char attachTo) :
      pin(attachTo)
    {
    };

    void setup() {
      FastLED.addLeds<NEOPIXEL, pin>(leds, 10);
    };

};

//LedStrip ledstrip(LED_STRIP_PIN, LED_STRIP_NUM_LEDS);
LedStrip ledstrip(LED_STRIP_PIN);

void setup() {

}

void loop() {

}

我已尝试阅读可能导致此错误的原因,但坦率地说,我对此一无所知。据我了解,似乎我不能在那里使用 const (我认为我不是),因为它可能会在代码执行期间被修改。

完整的错误看起来像thissketch_feb03b.ino: In member function 'void LedStrip::setup()':

sketch_feb03b:20:33: error: use of 'this' in a constant expression

       FastLED.addLeds<NEOPIXEL, pin>(leds, 10);

                                 ^~~

【问题讨论】:

  • 模板参数(在本例中为 pin)必须为 constexpr。在您的情况下,pin 的值直到运行时才知道,这是不允许的。

标签: c++ arduino fastled


【解决方案1】:

您的问题是pin 不是编译时常量,所有模板参数都必须是编译时常量。

可能还有其他选项,但(可能)最简单的一个是将 pin 作为模板参数本身传递:

template<int pin> // make sure type of pin is correct, I don't know what addLeds expect
class LedStrip {
  public:
    LedStrip() //not really needed now
    {
    };

    void setup() {
      FastLED.addLeds<NEOPIXEL, pin>(leds, 10);
    };
};

用法:

//if LED_STRIP_PIN is a compile-time constant, i.e. a macro or a const(expr) value
LedStrip<LED_STRIP_PIN> ledstrip;

//if LED_STRIP_PIN  is obtained at runtime, you cannot it use it at all.
LedStrip<7> ledstrip;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-17
    • 1970-01-01
    • 1970-01-01
    • 2014-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多