我有以下使用 Aaron Liddiment 的 LED libraries 的代码(为简单起见进行了精简) :
#include <FastLED.h>
#include <LEDMatrix.h>
#include <LEDSprites.h>
#include <LEDText.h>
cLEDMatrix<16, 16, HORIZONTAL_ZIGZAG_MATRIX> leds;
class Class2{
public:
Class2(){
init();
};
void init(){
cLEDSprites Sprites(&leds);
}
bool loop(){
Sprites.UpdateSprites();
return true;
}
};
我需要引用 Class2::loop()
中的 Sprites
对象,如图所示,但我被告知未声明 'Sprites'在这个范围内
(这是有道理的)。如果我将这一行移到 init
函数之外,如下所示:
class Class2{
cLEDSprites Sprites(&leds);
public:
Class2(){};
bool loop(){
Sprites.UpdateSprites();
}
};
然后我得到错误:'&'标记前的预期标识符
。
如果 Sprites
是一个 int
,我会在 Class2
中声明一个私有(private)属性,通过构造函数将值传递给类并复制它在 init
函数中结束。我不知道如何使用 cLEDSprites
类型的东西来做到这一点。如您所知,我对所有这些东西都很陌生,所以请原谅我的无知!
最佳答案
使用成员启动器列表语法,您的代码可能如下所示:
#include <FastLED.h>
#include <LEDMatrix.h>
#include <LEDSprites.h>
#include <LEDText.h>
cLEDMatrix<16, 16, HORIZONTAL_ZIGZAG_MATRIX> leds;
class Class2{
public:
Class2():
Sprites(&leds);
{
}
bool loop(){
Sprites.UpdateSprites();
return true;
}
private:
cLEDSprites Sprites;
};
成员初始化器列表可用于初始化任何类成员,尤其是那些不能默认初始化的成员(例如 const
成员或没有默认构造函数的类)。
在这里初始化所有内容是个好主意 - 有些人甚至会说好的构造函数的主体中从来没有任何行。
当然,最好不要使用全局变量,而只是将指向矩阵的指针传递给 Class2
构造函数,但我相信如果您决定,您将能够自己做到这一点不使用全局变量。
关于C++/Arduino 如何从类内部引用全局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57937496/