抽象类和构造函数

时间:2019-12-18 12:26:52

标签: c++ abstract-class

我们试图用C ++实现抽象超类的解决方案: 控制是样条线等的超类。 现在,当我们尝试实例化Spline类型的对象时,实例化失败,并出现两个错误:

  
      
  1. 无法为Spline类的构造函数找到具有匹配参数的方法
  2.   
  3. 无法分配抽象类型为“控件”的对象
  4.   

我们如何解决这些问题?

实例化Control类型的样条线,并在main中使用它:

RampFunction timeRampFn{0, 100, 2000, 1000};
RampFunction distanceRampFn{0, 0, 0.5f, 1000};

Control ctrl = new Spline(slowDownCoeff, timeRampFn, distanceRampFn);

ctrl.calculateAction(&newRobotState, p_0, p_t, targetTrack, timeFromStart, distanceToTarget);

Control.hpp(抽象超类):

#ifndef CONTROL_HPP
#define CONTROL_HPP

#include <vector>
#include <Data/Track.h>
#include <Data/TrackPoint.h>
#include <Data/RobotState.h>
#include <boost/multiprecision/eigen.hpp>

using Eigen::Vector2f;
using namespace std;

class Control
{
private:
const float FUTURE_INTERVAL = 0.1f;

protected:
const int FUTURE_SIZE = 10;

public:
virtual void calculateAction(RobotState *state, Vector2f curPos, Vector2f refPos, Track targetTrack, float timeFromStart, float distanceToTarget) = 0;
};

#endif

Spline.hpp:

#ifndef SPLINE_HPP
#define SPLINE_HPP

#include <Control/Control.hpp>

using Eigen::Vector2f;
using namespace std;

class Spline : Control
{
private:
struct RampFunction
{
    float x_0, val_0;
    float x_e, val_e;
};
float slowDownCoeff;
RampFunction timeRampFn;
RampFunction distanceRampFn;

public:
Spline(float slowDownCoeff, RampFunction timeRampFn, RampFunction distanceRampFn)
{
    this->slowDownCoeff = slowDownCoeff;
    this->timeRampFn = timeRampFn;
    this->distanceRampFn = distanceRampFn;
}
virtual void calculateAction(RobotState *state, Vector2f curPos, Vector2f refPos, Track targetTrack, float timeFromStart, float distanceToTarget);
};

#endif

2 个答案:

答案 0 :(得分:4)

Control ctrl = ...

您已经创建了Control类型的变量。不允许这样做,因为Control是抽象类型。这就是为什么出现错误cannot allocate an object of abstract type 'Control'的原因。

另一个问题是Control没有构造函数,该构造函数将接受类型为Spline*的参数。


您可能一直想做的是创建指向派生对象Control* ctrl = ...的基本指针。但是,这将导致删除动态分配成为问题,因为由于基的析构函数是非虚拟的,因此不允许您通过基指针进行删除。一种解决方案是将析构函数声明为虚拟。

但是仅允许删除是不够的。您应该实际执行删除操作,否则内存可能会泄漏。

答案 1 :(得分:2)

这应该是您想要的修改后的代码。

main.cpp

auto

Control.hpp

RampFunction timeRampFn{0, 100, 2000, 1000};
RampFunction distanceRampFn{0, 0, 0.5f, 1000};

Control *ctrl = new Spline(slowDownCoeff, timeRampFn, distanceRampFn);

ctrl->calculateAction(&newRobotState, p_0, p_t, targetTrack, timeFromStart, 
distanceToTarget);

Spline.hpp

#ifndef CONTROL_HPP
#define CONTROL_HPP

#include <vector>
#include <Data/Track.h>
#include <Data/TrackPoint.h>
#include <Data/RobotState.h>
#include <boost/multiprecision/eigen.hpp>

using Eigen::Vector2f;
using namespace std;

class Control
{
private:
const float FUTURE_INTERVAL = 0.1f;

protected:
const int FUTURE_SIZE = 10;

public:
virtual ~Control() {}
virtual void calculateAction(RobotState *state, Vector2f curPos, Vector2f refPos, Track targetTrack, float timeFromStart, float distanceToTarget) = 0;
};

#endif