繁体   English   中英

C ++抽象/具体类声明

[英]C++ Abstract / Concrete Class Declaration

我有一个MotorDefinition类和一个名为Motor的抽象类:

class MotorDefinition {
public:
    MotorDefinition(int p1, int p2, int p3) : pin1(p1), pin2(p2), pin3(p3) {}
    int pin1 = -1;
    int pin2 = -1;
    int pin3 = -1;
};
class Motor {
public:
     Motor(MotorDefinition d) : definition(d) {}
     virtual void forward(int speed) const = 0;
     virtual void backward(int speed) const = 0;
     virtual void stop() const = 0;
protected:
    MotorDefinition definition;
};

我的Zumo车有两个马达:

class MotorTypeZumoLeft : public Motor {
    MotorTypeZumoLeft(MotorDefinition def) : Motor(def) {}
    void Motor::forward(int speed) const {}
    void Motor::backward(int speed) const {}
    void Motor::stop() const {}
};

class MotorTypeZumoRight : public Motor {
    MotorTypeZumoRight(MotorDefinition def) : Motor(def) {}
    void Motor::forward(int speed) const {}
    void Motor::backward(int speed) const {}
    void Motor::stop() const {};
};

class MotorTypeZumo {
public:
     MotorTypeZumo(MotorTypeZumoLeft *l, MotorTypeZumoRight *r) : left(l), right(r) {}

protected:
    MotorTypeZumoLeft *left;
    MotorTypeZumoRight *right;

};

不幸的是(对我来说),这不编译:

MotorDefinition lmd(1, 2, 3);
MotorTypeZumoLeft *leftMotor(lmd);
MotorDefinition rmd(4, 5, 6);
MotorTypeZumoRight *rightMotor(rmd);
MotorTypeZumo motors(*leftMotor, *rightMotor);

我想我缺少一些基本概念,我当然搞砸了一些语法。 请帮我正确定义一下。

以下方法不起作用,因为您无法使用MotorDefinition实例初始化指针变量。

MotorTypeZumoLeft *leftMotor(lmd);

您可能并不打算将leftMotor作为指针。

MotorTypeZumoLeft leftMotor(lmd);

同样适用于rightMotor

MotorTypeZumoRight rightMotor(rmd);

您需要传递地址来初始化motors

MotorTypeZumo motors(&leftMotor, &rightMotor);

但是,如果您打算将leftMotorrightMotor作为指针,那么最好使用智能指针而不是原始指针。

auto leftMotor = std::make_unique<MotoTypeZumoLeft>(lmd);
auto rightMotor = std::make_unique<MotoTypeZumoRight>(lmd);

并且,您应该修改MotorTypeZumo以使用智能指针。

class MotorTypeZumo {
public:
     MotorTypeZumo(
          std::unique_ptr<MotorTypeZumoLeft> &l,
          std::unique_ptr<MotorTypeZumoRight> &r)
    : left(std::move(l)), right(std::move(r)) {}
protected:
    std::unique_ptr<MotorTypeZumoLeft> left;
    std::unique_ptr<MotorTypeZumoRight> right;
};

然后,您可以将leftMotorrightMotor传递给motors

MotorTypeZumo motors(leftMotor, rightMotor);

暂无
暂无

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

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