Class 会在 loop() 中初始化,但不会在 setup() 中初始化

Class will initialize when in loop(), but not in setup()

我在 Arduino 中创建了一个 class 并引入了 class。代码在以下情况下可以正常编译和运行:

#include <myclass.h>

void setup(){
// Do some setup if needed
}

void loop(){
myclass newInstance;
newInstance.setSomething();
newInstance.getSomething();
}

但 verify/compile 在以下情况下不会:

#include <myclass.h>

void setup(){
myclass newInstance;
newInstance.setSomething();
}

void loop(){
newInstance.getSomething();
}

错误:'newInstance' 未在此范围内声明。

我见过一些人在设置和循环之外实例化(在包含部分的正下方)。请解释创建实例然后在循环中使用它的最佳实践。我想在循环部分之外实例化,所以我不会在每个循环中创建一个实例。

您应该在全局范围内声明该对象。 C++中的变量声明(而Arduinos的语言基本上是C++)在scope

中有效

所以你的代码应该是这样的

#include <myclass.h>

myclass newInstance;

void setup(){

newInstance.setSomething();
}

void loop(){
newInstance.getSomething();
}