C++/Arduino 如何从类内部引用全局
C++/Arduino How to reference a global from inside a class
我有以下代码(为简单起见进行了精简(,它使用了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
但我相信,如果您决定不使用全局变量,您将能够自己做到这一点。
相关文章:
- 如何获得对不同类的引用,以便从所述类内部获得变量值
- C++/Arduino 如何从类内部引用全局
- 结构内部的结构:"对非静态成员的非法引用"错误
- 如果不允许我分配 rvalues 来引用为什么以下代码片段有效,这在内部如何工作?
- IFDEF块内部对功能的未定义引用
- 当在函数内部使用静态变量时,输出会发生变化,该函数在c++中返回引用
- 通过<T> Boost.Python 作为内部引用公开 boost::可选或 None
- 在函数内部创建一个局部向量,然后将其作为引用传递给其他函数,这些函数将其存储为引用
- 另一个结构内部的结构数组的成员变量没有通过引用传递
- 在 C++ 中作为指针或别名进行内部编译的引用
- 如何通过参数内部的引用传递对象
- c++在函数内部创建引用变量
- 如何将相互依赖的对象移动到一起并维护内部引用
- 引用对象内部的指针
- c++引用函数内部的函数
- 包含内部引用的初始值设定项列表
- 如何修改/更新通过 const 引用传递的对象的内部状态
- 修改对内部数据的引用时更新 STL 优先级队列
- 矢量迭代器不可解引用(矢量内部的矢量)
- lambda内部引用捕获对象的类型