c++ - 错误:在 Arduino 类的常量表达式中使用“this”
问题描述
我正在尝试为 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:在成员函数'void LedStrip::setup()'中:
sketch_feb03b:20:33: error: use of 'this' in a constant expression
FastLED.addLeds<NEOPIXEL, pin>(leds, 10);
^~~
解决方案
您的问题是这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;
推荐阅读
- flutter - 颤动关闭警报对话框而不弹出屏幕
- python - 当输入条件为真时,'If'循环'和不打印消息
- css - 多行响应::边框前
- node.js - TypeORM : 使用嵌套的 AND 和 OR 生成查询
- python - 在数据预处理中调整图像大小以训练卷积网络
- java - 如何将 MySQL 数据库中的值存储到变量中?
- flutter - 使用 Flutter 将文本基线与列内的文本对齐
- javascript - 悬停事件侦听器和任何事件侦听器都不起作用
- arrays - 是否可以引用嵌套数组中的索引位置?红宝石
- amazon-web-services - 域名未连接到 node.js express web 应用程序