(1)先建立一个Point(点)类,包含数据成员x,y(坐标点);
(2)以Point为基类,派生出一个Circle(圆)类,增加数据成员(半径),基类的成员表示圆心;
(3)编写上述两类中的构造、析构函数及必要运算符重载函数(本项目主要是输入输出);
运行结果:
(2)以Point为基类,派生出一个Circle(圆)类,增加数据成员(半径),基类的成员表示圆心;
(3)编写上述两类中的构造、析构函数及必要运算符重载函数(本项目主要是输入输出);
(4)定义友元函数int locate,判断点p与圆的位置关系(返回值<0圆内,==0圆上,>0 圆外);
代码
#include <iostream>
#include <cmath>
using namespace std;
class Point
{
protected:
double x,y;
public:
Point(double xx,double yy):x(xx),y(yy) {}
double getx(){return x;}
double gety(){return y;}
friend ostream & operator<<(ostream &,const Point &);
};
ostream & operator<<(ostream &output,const Point &p)
{
output<<"["<<p.x<<","<<p.y<<"]"<<endl;
return output;
}
class Circle:public Point
{
protected:
double r;
public:
Circle(double xx,double yy,double rr):Point(xx,yy),r(rr) {}
friend ostream &operator<<(ostream &out,Circle &c);
friend int locate(Point &p,Circle &c);
};
ostream &operator<<(ostream &out,Circle &c)
{
out<<"圆心=("<<c.getx()<<","<<c.gety()<<") 半径="<<c.r<<endl;
return out;
}
int locate(Point &p,Circle &c)
{
double x=p.getx()-c.getx(),y=p.gety()-c.gety(),s;
s=sqrt(x*x+y*y);
if(abs(s-c.r)<=0.00001)
return 0;
else if(s>c.r)
return 1;
else
return -1;
}
int main( )
{
Circle c1(3,2,4),c2(4,5,5); //c2应该大于c1
Point p1(1,1),p2(3,-2),p3(7,3); //分别位于c1内、上、外
cout<<"圆c1: "<<c1;
cout<<"点p1: "<<p1;
cout<<"点p1在圆c1之"<<((locate(p1, c1)>0)?"外":((locate(p1, c1)<0)?"内":"上"))<<endl;
cout<<"点p2: "<<p2;
cout<<"点p2在圆c1之"<<((locate(p2, c1)>0)?"外":((locate(p2, c1)<0)?"内":"上"))<<endl;
cout<<"点p3: "<<p3;
cout<<"点p3在圆c1之"<<((locate(p3, c1)>0)?"外":((locate(p3, c1)<0)?"内":"上"))<<endl;
return 0;
}
运行结果: