6-1 类的继承和派生
本题实现类的额继承和派生。已经给出相关的数据结构和类的声明,要求实现类的相关函数,为保证比较的结果,所有的数据均以int类型(除了PI取3.14外),程序运行时,输入一个点p的坐标x和y,接着是圆的中心坐标和半径,接着是三角形的三个顶点,程序运行显示圆的面积和周长,点p是否位于园内,三角形的面积和周长,以及p是否位于三角形内。
函数接口定义:
在这里给出了数据结构和类的声明,以及一个全局函数的声明:
#include <iostream>
#include <math.h>
using namespace std;
const double PI = 3.14;
struct Point{//点的定义
int x,y;
};
int distance(Point p1,Point p2);//计算两个点之间的距离
class Shape
{
public:
int area(){return 0;}//计算图形面积
int length(){return 0;}//计算图形的周长
void show(){}//显示相关信息
bool IsInside(Point p){return false;}//点p是否位于图形内,如果是,返回true
};
class Circle:public Shape{
Point center;//圆心
int radius;//半径
public:
Circle(Point,int);
int area();
int length();
void show();
bool IsInside(Point p);
};
class TriAngle:public Shape{
Point a,b,c;//三角形的三个顶点
public:
TriAngle(Point,Point,Point);
int area();
int length();
void show();
bool IsInside(Point p);
};
裁判测试程序样例:
在这里给出函数被调用进行测试的例子。例如:
int main()
{
Point p,center,a,b,c;
int r;
cin>>p.x>>p.y;
cin>>center.x>>center.y;
cin>>r;
cin>>a.x>>a.y>>b.x>>b.y>>c.x>>c.y;
Circle c1(center,r);
c1.show();
if(c1.IsInside(p))
cout<<"p inside circle"<<endl;
else
cout<<"p not inside circle"<<endl;
TriAngle tri(a,b,c);
tri.show();
if(tri.IsInside(p))
cout<<"p inside triangle"<<endl;
else
cout<<"p not inside triangle"<<endl;
return 0;
}
/* 请在这里填写答案 */
我的代码:
Circle::Circle(Point p, int r) { center = p, radius = r; }
int Circle::area() {
int area = radius * radius * PI;
return area;
}
int Circle::length() {
int length = PI * 2 * radius;
return length;
}
void Circle::show() {
cout << "Circle:area=" << area() << ",length=" << length()<<'\n';
}
int distance(Point p1, Point p2){
int dis = sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y));
return dis;
}
bool Circle::IsInside(Point p) {
if (distance(p, center) <= radius) {
return true;
}
else {
return false;
}
}
TriAngle::TriAngle(Point t1,Point t2,Point t3):a(t1),b(t2),c(t3){}
int TriAngle::area() {
int area1 = 0.5*(a.x * (b.y - c.y) +b.x*(c.y-a.y)+c.x*(a.y-b.y) );
if (area1 >= 0) {
return area1;
}
else {
area1 = (-1) * area1;
return area1;
}
}
int TriAngle::length() {
int length = distance(a, b) + distance(b, c) + distance(c, a);
return length;
}
void TriAngle::show() {
cout << "TriAngle:area=" << TriAngle::area() << ",length=" << TriAngle::length() << endl;
}
bool TriAngle::IsInside(Point p) {
double s1 = 0.5* (p.x * (b.y - c.y) + b.x * (c.y - p.y) + c.x * (p.y - b.y));
if (s1 < 0) {
s1 = s1 * (-1);
}
else {
s1 = s1;
}
double s2 =0.5 * (a.x * (p.y - c.y) + p.x * (c.y - a.y) + c.x * (a.y - p.y));
if (s2< 0) {
s2 = s2 * (-1);
}
else {
s2 = s2;
}
double s3 = 0.5* (a.x * (b.y - p.y) + b.x * (p.y - a.y) + p.x * (a.y - b.y));
if (s3 < 0) {
s3 = s3 * (-1);
}
else {
s3 = s3;
}
int sum = s1 + s2 + s3;
if (TriAngle::area()==sum) {
return true;
}
else {
return false;
}
}
输入样例:
10 10 10 10 5 10 1 1 10 15 15
输出结果:
不足之处,望指正!