在嵌入式c项目中,我有几种不同类型的电机。 该实现具有静态变量和const变量,并支持子类型。
它看起来像这样(简化):
// 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);
}
虽然代码有效,但很难阅读。 我认为面向对象的语言更有意义吗?
所以我的问题是:
答案 0 :(得分:2)
将建议以下类结构。代替功能指针,只需重新实现设定速度功能即可。
//! 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);
};