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

Declaration of global members inside a class in c++

本文关键字:全局 成员 C++ 声明      更新时间:2023-10-16

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

#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();
};

这是我的示例.cpp,其中我使用电机和控制器,它们是全局对象:


#include <example.h>
void Example::moveMotor(){
::motor.setTargetRel(1024);
::controller.move(::motor);
}

这是我的主要.cpp文件:

#include <example.h>
Stepper motor(stepPin, dirPin);
StepControl controller;
Example exampleObject();
void setup(){
pinMode(enabPin, OUTPUT);
pinMode(stepPin, OUTPUT);
pinMode(chipSelect, OUTPUT);
pinMode(dirPin, OUTPUT);
pinMode(sensor, INPUT_PULLUP);
pinMode(led, OUTPUT);
pinMode(channelA, INPUT);
pinMode(channelB, INPUT);
pinMode(startStop, OUTPUT);
pinMode(dirSwitch, OUTPUT);
pinMode(encoButton, INPUT);
};
void loop(){
exampleObject.moveMotor();
};

我知道我做错了什么,但我不知道在哪里寻找解决方案,欢迎任何帮助。谢谢。

在上面介绍的文件中,我正在创建一个名为Example的类,它只有一个依赖于两个对象的函数,StepperStepControl。这两个对象必须全局声明,因为它们具有静态成员。出于这个原因,我正在编写调用全局对象的类的函数:


#include <example.h>
void Example::moveMotor(){
::motor.setTargetRel(1024);
::controller.move(::motor);
}

但是,当我编译程序时,编译器告诉我

'motor' has not been declared. The global scope has no 'motor'

如何使类的成员成为全局对象?

我正在为 linux 编写可视化代码程序,其中包含一个名为 platformIO 的物理计算扩展,我正在使用的库称为 TeensyStep。

你的前提被打破了:

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

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

目前尚不清楚您在哪里声明Stepper,但是当您尝试访问其成员时,似乎缺少#include。如果setTargetRel()是一种staticStepper的方法,那么您可以像这样称呼它:

Stepper::setTargetRel(1024);

如果setTargetRel不是静态方法,则需要一个实例来调用它。您仍然不应该将此实例设置为全局变量,而是将其作为Example的成员或将其作为参数传递给Example::moveMotor

添加到example.h
extern Stepper motor;

添加到example.cpp
Stepper motor(stepPin, dirPin);

void Example::moveMotor() {
motor.setTargetRel(1024); // remove :: before motor

main.cpp中删除:
Stepper motor(stepPin, dirPin);

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

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

class Example {
public:
Example() : 
motor(stepPin, dirPin),
controller{}
{}  
void moveMotor(int target=1024) {
motor.setTargetRel(target);
controller.move(motor);
}
private:
Stepper motor;
StepControl controller;
};