背景
最近帮密院的小同学看了一下他们的C++作业,对大一的新生来说还是不太友好。
作业要求是用openGL实现一个2D停车场程序,停车场里面有各种机动车(由不同的几何形状组成)。然后所有机动车可以沿圆滑轨迹被调度运动,倒车入库什么的。
继承关系
所有机动车继承自一个Group类,并且Group继承自一个Figure接口类。
问题
在构造机动车类的时候,需要对Group的std::vector<Figure*> 进行初始化,因此需要显示构造父类Group。
方法
方法一:列表初始化
// C++ 从祖先开始构造,可以在列表初始化中直接调用父类的对应构造函数
Vehicle::Vehicle(const std::vector<Figure*> &_figure_ptrs):Group(_figure_ptrs) {}
方法二:using 继承父类构造函数
class Gourp: public Figure
{
public:
Group(const std::vector<Figure*> &_figure_ptrs): figure_ptrs(_figures_ptrs) {}
private:
std::vector<Figure*> figure_ptrs;
};
class Vehicle: public Group
{
public:
using Gourp::Group;
};
// sample
std::vector<Figure*> m_figure_ptrs = {a, b, c};
Vehicle(m_figure_ptrs);
方法三:继承加委托构造
class Gourp: public Figure
{
public:
Group(const std::vector<Figure*> &_figure_ptrs): figure_ptrs(_figures_ptrs) {}
private:
std::vector<Figure*> figure_ptrs;
};
class Vehicle: public Group
{
public:
using Gourp::Group;
Vehicle(const std::vector<Figure*> &_figure_ptrs, const Trajectory &trj):Group(_figure_ptrs), _trj(trj){}
void actionByTrajectory(){}
private:
Trajectory _trj;
};
// sample
std::vector<Figure*> m_figure_ptrs = {a, b, c, ...};
Trajectory trj = {point1, point2, point3, point4 ...};
Vehicle(m_figure_ptrs, trj);