C++ c+中类内全局成员的声明+;

C++ c+中类内全局成员的声明+;,c++,class,forward-declaration,scopes,C++,Class,Forward Declaration,Scopes,我正在尝试编程一个微控制器来移动一个电机,并用一个编码器和一些电位器执行其他功能。我想使用一个通过脉宽调制信号向电机驱动器发送脉冲的库,但据我所知,这个库的类依赖于静态变量,我不知道如何从我自己的类访问静态变量。这是我的标题的简化: #include <Arduino.h> #include <Teensystep.h> #define startStop 2 #define stepPin 3 #define

我正在尝试编程一个微控制器来移动一个电机,并用一个编码器和一些电位器执行其他功能。我想使用一个通过脉宽调制信号向电机驱动器发送脉冲的库,但据我所知,这个库的类依赖于静态变量,我不知道如何从我自己的类访问静态变量。这是我的标题的简化:

#include <Arduino.h>
#include <Teensystep.h>
#define startStop               2
#define stepPin                 3
#define dirPin                  4
#define channelA                5
#define channelB                6
#define enabPin                 7
#define dirSwitch               8
#define soundTrig               9
#define chipSelect              10
#define mosiSdi                 11
#define misoSdo                 12
#define clk                     13

#define led                     A3
#define potSpeed                A4
#define encoButton              A5
#define sensor                  A7

class Example{

public:  

        void moveMotor();

};

然而,当我编译程序时,编译器告诉我

'motor' has not been declared. The global scope has no 'motor'
如何使类的成员成为全局对象


我正在使用Visual Code for linux编写程序,其中包含一个物理计算扩展名为platformIO,我正在使用的库名为platformIO。

你的前提被打破了:

这两个对象必须全局声明,因为它们有静态成员

不需要。当类有静态成员时,实际上不需要任何对象来访问这些成员

不清楚您在哪里声明了
Stepper
,但在尝试访问其成员时,您似乎缺少了
#include
。如果
setTargetRel()
Stepper
static
方法,那么您可以这样称呼它:

 Stepper::setTargetRel(1024);

如果
setTargetRel
不是一个静态方法,那么需要一个实例来调用它。但是,您不应该将此实例设置为全局变量,而是将其设置为
示例的成员,或者将其作为参数传递给
示例::移动马达

添加到
示例。h

extern步进电机

添加到
示例.cpp

步进电机(stepPin、dirPin)

main.cpp中删除:
步进电机(stepPin、dirPin)

这应该允许包括
example.h
在内的所有文件使用全局变量
motor
——但总体设计有问题

如果
Example
负责设置目标和初始化移动,为什么它不同时拥有
Stepper
StepControl
实例,并提供方便的功能来将操作保持在一起?例如:

class Example {
public:
  Example() : 
    motor(stepPin, dirPin),
    controller{}
  {}  

  void moveMotor(int target=1024) {
    motor.setTargetRel(target);
    controller.move(motor);
  }

private:
  Stepper motor;
  StepControl controller;
};

不相关的:代码中的“代码”>定义为 S,看起来很像你应该考虑把它变成一个@ USER881301,谢谢你的建议。你能给我解释一下为什么在这种情况下,
enum
#define
好吗?
#define
是一种简单的文本替换,它发生在所有其他事情之前。没有健全的检查或更智能的逻辑应用于替代。无论在代码中的任何地方发现
startStop
,它都会被
2
替换,无论替换多么愚蠢或疯狂。如果您意外地重用
startStop
,例如一个函数
void startStop()
,结果可能会非常奇怪,编译器会将前面的函数视为
void 2()
,错误信息几乎总是误导人的<代码>枚举
在编译过程中进行处理,并在使用前进行更彻底的检查。非常感谢您的回答,我会尽快尝试。因此,如果我理解正确,可以使用
Stepper::setTargetRel()
调用成员
setTargetRel
,而无需创建
Stepper
对象?@AntonioCastles,我不知道。如果是静态方法,则是
'motor' has not been declared. The global scope has no 'motor'
 Stepper::setTargetRel(1024);
void Example::moveMotor() {
    motor.setTargetRel(1024); // remove :: before motor
class Example {
public:
  Example() : 
    motor(stepPin, dirPin),
    controller{}
  {}  

  void moveMotor(int target=1024) {
    motor.setTargetRel(target);
    controller.move(motor);
  }

private:
  Stepper motor;
  StepControl controller;
};