C++ 子类调用基类的构造函数 (交大密院大一上寄倒)

背景

最近帮密院的小同学看了一下他们的C++作业,对大一的新生来说还是不太友好。

作业要求是用openGL实现一个2D停车场程序,停车场里面有各种机动车(由不同的几何形状组成)。然后所有机动车可以沿圆滑轨迹被调度运动,倒车入库什么的。

继承关系

«interface»
Figure
-Point anchor
+bool move(Vec director)
+bool rotate(float angle)
+bool zoom(float k)
Group
-std::vector<Figure*>
+bool move(Vec director)
+bool rotate(float angle)
+bool zoom(float k)
+sth get_sth()
+void set_sth()
«Abstract»
ColoredFig
-Color m_color;
+anything get_anything()
Quadrilateral
Parallelogram
Rectangel
Triangle
Circular
Vehicle
+bool move(Vec director)
+bool rotate(float angle)
+bool zoom(float k)

所有机动车继承自一个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);
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值