15.把描述直角坐标系上的一个点的类作为基类,派生出描述一条直线的类和描述一个三角形的类.

该程序定义了描述直角坐标系上点的Point类,并以此为基础派生出描述直线的Line类和描述三角形的Triangle类。每个类都有相应的构造函数用于初始化坐标。Triangle类中实现了计算三角形面积的方法,使用海伦公式。在主函数中,创建了一个Triangle对象并输出其坐标和面积,测试了类的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

15.把描述直角坐标系上的一个点的类作为基类,派生出描述一条直线的类和描述一个三角形的类。
定义成员函数求出两点间的距离和三角形的面积。
提示:先定义描述点的类Point;类Point的派生类Line为直线类,一直线有两个端点,所以它在点
类的基础上新增一组点的坐标(x2,y2);三角形类T在直线的基础上再新增一组点的坐标
(x3,y3),求出三角形的面积。具体要求如下,
(1)定义点类Point int xl,y1://保护的数据成员(点坐标)  公有构造函数 Point(int aint b): //初始化xl、yl
(2)定义直线类Line  int x2,y2;//保护的数据成员(点坐标)。● 公有构造函数 Line(int aint b.int c.int d);//初始化 x2、v2,以及x1、yl
(3)定义三角形类Triangle  int x3,y3; //私有的数据成员(点坐标)  double area; //私有的数据成员(面积)
公有构造函数Triangle(int aint bint cint d,int eint f)://初始化x3、y3,以及 xl、yl,x2、y2
void f(): //求三角形面积的功能函数,先求出三条边 x、y、z,然后用以下公式求 
面积:s=(x+y+z)/2   area=sqrt(s(s-x)(s-y)(s-z))  void print(:)//输出三个点的坐标和面积
(4)在主函数中对该类进行测试。定义一个Triangle类的对象tri,
以1和1,4和1以及4和5作为点的坐标,完成测试工作。程序运行输出:
(1,1) (4,1) (4,5) 
area=6

#include<iostream>
#include<math.h>
using namespace std;
class Point
{
protected:
	int x1, y1;
public:
	Point(int x1, int y1) :x1(x1), y1(y1) {}
	void display()
	{
		cout << "(" << this->x1 << "," << this->y1 << ")" << endl;
	}
};
class Line:public Point
{
protected:
	int x2, y2;
public:
	Line(int x1,int y1,int x2,int y2):Point(x1,y1),x2(x2),y2(y2){}
	void display()
	{
		cout << "(" << this->x1 << "," << this->y1 << ")" << endl;
		cout << "(" << this->x2 << "," << this->y2 << ")" << endl;
	}
};
class Triangle:public Line
{
protected:
	int x3, y3;
	double area;
public:
	Triangle(int a, int b, int c, int d, int e, int f) : Line(a,b,c, d), x3(e), y3(f) {}
	void f()
	{
		double temp1, temp2, temp3,S;
		temp1 = sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
		temp2 = sqrt((x3 - x1) * (x3 - x1) + (y3 - y1) * (y3 - y1));
		temp3 = sqrt((x2 - x3) * (x2 - x3) + (y2 - y3) * (y2 - y3));
		S = (temp1 + temp2 + temp3) * 0.5;
		area = sqrt(S * (S - temp1) * (S - temp2) * (S - temp3));
	}
	void print() { cout <<"三角形面积为:\t"<< this->area << endl; }
	void display()
	{
		cout << "(" << this->x1 << "," << this->y1 << ")" << endl;
		cout << "(" << this->x2 << "," << this->y2 << ")" << endl;
		cout << "(" << this->x3 << "," << this->y3 << ")" << endl;
	}
};
int main()
{
	Triangle tri(1, 1, 4, 1, 4, 5);
	tri.display();
	tri.f();
	tri.print();
	system("pause");
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值