简体   繁体   English

具有静态和const成员变量的对象

[英]Object with static and const member variables

In an embedded c project I have several motors of different type. 在嵌入式c项目中,我有几种不同类型的电动机。 The implementation has static and const variables, and supports sub types. 该实现具有静态和const变量,并支持子类型。

It looks something like this (simplified): 看起来像这样(简化):

// motor.h

// to be global/static
typedef struct
{
    int distance;
} motor_instance;

// to be const
typedef const struct motor_hwToken_s
{
    motor_instance *self;
    void (*setSpeedFunction)(const struct motor_hwToken_s *token, int speed);
    int hwPin;
} motor_hwToken_t;

extern motor_hwToken_t motor_A;
void setSpeed(const struct motor_hwToken_s *token, int speed);


// motor.c
void setSpeed(const struct motor_hwToken_s *token, int speed)
{
    token -> setSpeedFunction(token, speed);
}

// specialization for DC-motors
void setSpeed_dcMotor(const struct motor_hwToken_s *token, int speed);

// global variable
motor_dc_instance motor_A_instance;

// const variable, known at compile time
motor_hwToken_t motor_A =
{
    .self = &motor_A_instance,
    .setSpeedFunction = setSpeed_dcMotor,
    .hwPin = 0x04       // define an IO-Pin of some sort
};


// main.c
void main(void)
{
    setSpeed(&motor_A, 20);
}

While the code works, it's quite hard to read. 虽然代码有效,但很难阅读。 I assume an object oriented language would make more sense? 我认为面向对象的语言会更有意义吗?

So my question is: 所以我的问题是:

  1. How could I implement this in c++? 我如何在C ++中实现呢?
  2. Will the cpp compiler be able to optimize the const variables (eg put them in flash)? cpp编译器是否可以优化const变量(例如,将其放入Flash)?

The following class structure would be suggested. 建议使用以下类结构。 Instead of function pointer just re-implement the set speed function. 代替功能指针,只是重新实现设定速度功能。

//! Motor interface class with abstract functions.
class Motor {
  public:
    virtual ~Motor() = default;
    void set_hwPin(int pin) { hwPin = pin; };
    virtual void set_speed(int speed) = 0;

  private:
    int hwPin;
};

class MotorDC : public Motor {
  public:
    ~MotorDC() override = default;
    void set_speed(int speed) override {
      // Actual implementation for DC motors.
    }
};

class MotorAC : public Motor {
  public:
    ~MotorAC() override = default;
    void set_speed(int speed) override {
      // Actual implementation for AC motors.
    }
};

int main() 
{
  MotorDC mDC;
  mDC.set_pin(1);

  MotorAC mAC;
  mAC.set_pin(2);

  // To demonstrate use a pointer to the abstract base class.
  Motor* m;
  m = &mAC;
  m->set_speed(10);

  m = &mDC;
  m->set_speed(20);
};

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

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