基类和派生类

C++复习时的遗忘,真让人无奈啊。

题目
定义一个“点”类Dot,包含数据成员x,y(坐标点),在平面上两点连成一条直线,定义一个直线类Line,求直线的长度和直线中点坐标, 数据自拟。
(提示:直线类继承Dot类,同时以Dot类作为其子对象)

这道题目写的时候基类里面的数据类型是protected类型的,所以就加上了取值的函数,看起来很麻烦。

#include <iostream>
#include <stdio.h>
#include <math.h>
using namespace std;
class Dot {
	protected:
		double x,y;
	public:
		Dot(){}
		Dot(double x1,double x2):x(x1),y(x2){}
		void display() {
			cout<<x<<" "<<y<<endl;
		}
		double getx() {
			return x;
		}
		double gety() {
			return y;
		}
};

class Line:public Dot {
	private:
		Dot p1,p2;
		double len;
	public:
		Line(double x1,double y1,double x2,double y2):p1(x1,y1),p2(x2,y2){}
		Line(Dot a,Dot b):p1(a.getx(),a.gety()),p2(b.getx(),b.gety()){}
		void Mid() {
			x=(p1.getx()+p2.getx())/2;
			y=(p1.gety()+p2.gety())/2;
		}
		void Length() {
			len=sqrt(pow(fabs(p1.getx()-p2.getx()),2)+pow(fabs(p1.gety()-p2.gety()),2));
		}
		void display() {
			printf("%.2lf %.2lf %.2lf\n",x,y,len);
		}
};

int main()
{
	Dot d1(0,0),d2(3,4);
	d1.display();
	d2.display();
	Line l(d1,d2);
	l.Length();
	l.Mid();
	l.display();
	return 0;
}
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值