(5)在圆类上重载关系运算符(6种),使之能够按圆的面积比较两个圆的大小。自编main函数完成测试。
解决代码:
#include<iostream>
#include <cmath>
using namespace std;
class Point
{
public:
Point(double a=0,double b=0):x(a),y(b){};
double distance(Point &p);
friend ostream &operator<<(ostream &,const Point &);
protected:
double x;
double y;
};
ostream &operator<<(ostream &output,const Point &p)
{
output<<"("<<p.x<<","<<p.y<<")"<<endl;
return output;
}
double Point::distance(Point &p)
{
return sqrt((x-p.x)*(x-p.x)+(y-p.y)*(y-p.y));
}
class Circle:public Point
{
public:
Circle(double a,double b,double c):Point(a,b),r(c){};
double area();
friend ostream &operator<<(ostream &,const Circle &);
friend int locate(Point &p,const Circle &c);
bool operator>(const Circle &);
bool operator<(const Circle &);
bool operator>=(const Circle &);
bool operator<=(const Circle &);
bool operator==(const Circle &);
bool operator!=(const Circle &);
protected:
double r;
};
ostream &operator<<(ostream &output,const Circle &c)
{
output<<"center:("<<c.x<<","<<c.y<<"),r="<<c.r<<endl;
return output;
}
double Circle::area()
{
return 3.1415926*r*r;
}
bool Circle::operator>(const Circle &c)
{
return (this->r - c.r) > 1e-7;
}
bool Circle::operator<(const Circle &c)
{
return (c.r - this->r) > 1e-7;
}
bool Circle::operator>=(const Circle &c)
{
return !(*this < c);
}
bool Circle::operator<=(const Circle &c)
{
return !(*this > c);
}
bool Circle::operator==(const Circle &c)
{
return abs(this->r - c.r) < 1e-7;
}
bool Circle::operator!=(const Circle &c)
{
return abs(this->r - c.r) > 1e-7;
}
int locate(Point &p,const Circle &c)
{
Point cp(c.x,c.y);
double d=cp.distance(p);
if(abs(d-c.r)<1e-7)
return 0;
if(d<c.x)
return -1;
if(d>c.x)
return 1;
}
int main( )
{
Circle c1(3,2,4),c2(4,5,5); //c2应该大于c1
cout<<"圆c1( "<<c1<<" )的面积是 "<<c1.area()<<endl;
cout<<"圆c2( "<<c2<<" )的面积是 "<<c2.area()<<endl;
cout<<"圆c1 ";
if(c1>c2) cout<<"大于, ";
if(c1<c2) cout<<"小于, ";
if(c1>=c2) cout<<"大于等于, ";
if(c1<=c2) cout<<"小于等于, ";
if(c1==c2) cout<<"等于, ";
if(c1!=c2) cout<<"不等于, ";
cout<<"圆c2"<<endl;
return 0;
}
运行结果: