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");
}