第四次作业

第四次作业

1.问题概述:

第四次作业有关主题为继承与派生,因此我想就私有继承方式展开一下讨论,试一下私有继承究竟与公有继承有什么区别。

2.问题解析:

首先我定义了两个头文件point类和rectangle类:
在这里插入图片描述
在这里插入图片描述
使rectangle以私有继承方式来继承point类,并在main函数中实现:
在这里插入图片描述
但此时编译器会显示rectangle类中有错误:
在这里插入图片描述
在阅读完书和自行检查后发现,再私有继承之后,原本基类公有成员和保护成员全部变成了派生类的私有成员,所以导致了不能再派生类中直接调用。
进行修改之后,程序恢复正常运行并输出正确结果。
在这里插入图片描述
代码如下:

class point {
public:
	void initpoint(float x = 0, float y = 0) 
	{
		this->x = x;this->y = y;
	}
	void move(float offx = 0, float offy = 0)
	{
		x += offx;y += offy;
	}
	float getx() const { return x; }
	float gety() const { return y; }

private:
	float x;
	float y;
};
#include "point.h"
class rectangle :private point{
public:
	void initrectangle(float x, float y, float w, float h)
	{
		initpoint(x, y);
		this->w = w;
		this->h = h;
	}
	void move(float offx, float offy)
	{
		point::move(offx, offy);
	}
	float getx()const { return point::getx(); }
	float gety()const { return point::gety(); }
	float getw()const { return w; }
	float geth()const { return h; }
	private:
		float w,h;
};
#include "pch.h"
#include <iostream>
#include"point.h"
#include"rectangle.h"

using namespace std;

int main()
{
	rectangle rect;
	rect.initrectangle(2, 3, 20, 10);
	rect.move(3, 2);
	cout << "the data of rect(x,y,w,h)" << endl;
	cout << rect.getx() << ","
		<< rect.gety() << ","
		<< rect.getw() << ","
		<< rect.geth() << endl;
	return 0;
}

3.问题总结:

在继承方式上虽然通过老师的讲解可以大概懂得基本思路,但在实际操作中还是遇到了不少令人困惑的地方,本次实验我将书中的代码改造了一些并看看能否得出相同的结论,最终验证了老师所讲和书上所得结论的正确性。

posted @ 2019-10-12 10:21  超级无敌57  阅读(106)  评论(0编辑  收藏  举报