15.把描述直角坐标系上的一个点的类作为基类,派生出描述一条直线的类和描述一个三角形的类。定义成员函数求出两点间的距离和三角形的面积。提示:先定义描述点的类 Point;类 Point 的派生类 Line 为直线类,一直线有两个端点,所以它在点类的基础上新增一组点的坐标(x2,y2);三角形类 T 在直线的基础上再新增一组点的坐标(x3,y3), 求出三角形的面积。
具体要求如下:
- 定义点类 Point
- int x1,y1; //保护的数据成员(点坐标)
- 公有构造函数 Point(int a,int b)://初始化 x1、 y1
- 定义直线类 Line
- int x2,y2;//保护的数据成员(点坐标)。
- 公有构造函数 Line(int a,int b,int c,int d)://初始化 x2、 y2,以及 x1、 y1
- 定义三角形类 Triangle
- int x3,y3; //私有的数据成员(点坐标)
- double area; //私有的数据成员(面积)
- 公有构造函数 Triangle( int a,int b,int c,int d, int e,int f)://初始化 x3、 y3,以及
x1、 y1, x2、 y2 - void f(): //求三角形面积的功能函数,先求出三条边 x、 y、 z,然后用以下公式求
面积:
s=(x+y+z)/2
area= sqrt( s(s-x)(s-y)(s-z) ) - void print()://输出三个点的坐标和面积
- 在主函数中对该类进行测试。定义一个 Triangle 类的对象 tri,以1和1,4和1,以及4和5作为
点的坐标,完成测试工作。程序运行输出:
(1,1) ( 4,1) ( 4,5)
area=6
#include<iostream>
#include<cmath>
using namespace std;
class Point{
protected:
int x1,y1;
public:
Point(int a,int b):x1(a),y1(b){}
};
class Line:public Point{
protected:
int x2,y2;
public:
Line(int a,int b,int c,int d):Point(a,b),x2(c),y2(d){}
};
class Triangle:public Line{
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){}
double getDis(int x1,int x2,int y1,int y2){
return sqrt(pow(x2-x1,2)+pow(y2-y1,2));
}
void f(){
double a=getDis(x1,x2,y1,y2),b=getDis(x1,x3,y1,y3),c=getDis(x3,x2,y3,y2);
double s=(a+b+c)/2;
area = sqrt(s*(s-a)*(s-b)*(s-c));
}
void print(){
cout<<x1<<","<<y1<<endl;
cout<<x2<<","<<y2<<endl;
cout<<x3<<","<<y3<<endl;
cout<<"area="<<area<<endl;
}
};
int main(){
Triangle tri(1,1,4,1,4,5);
tri.f();
tri.print();
return 0;
}