繁体   English   中英

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

[英]Declaration of global members inside a class in c++

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

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

};

这将是我的 example.cpp,我使用电机和控制器,它们是全局对象:


#include <example.h>

void Example::moveMotor(){

    ::motor.setTargetRel(1024);
    ::controller.move(::motor);
}

这是我的 main.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'

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

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

你的前提被打破了:

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

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

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

 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;
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM