C++/Arduino 如何从类内部引用全局

C++/Arduino How to reference a global from inside a class

本文关键字:内部 引用 全局 Arduino C++      更新时间:2023-10-16

我有以下代码(为简单起见进行了精简(,它使用了Aaron Liddiment的LED库:

#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' was not declared in this scope(这是有道理的(。如果我将这一行移到init函数之外,如下所示:

class Class2{
cLEDSprites Sprites(&leds);
public:
Class2(){};
bool loop(){
Sprites.UpdateSprites();
}
};

然后我得到error: expected identifier before '&' token.

如果Sprites是一个int,我会在Class2中声明一个私有属性,通过构造函数将值传递到类中,并在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但我相信,如果您决定不使用全局变量,您将能够自己做到这一点。