问题及代码:
/* *Copyright (c)2015,烟台大学计算机与控制工程学院 *All rights reserved. *文件名称:project.cpp *作 者:陈文青 *完成日期:2015年5月31日 *版 本 号:v1.0 * *问题描述: (5)在圆类上重载关系运算符(6种),使之能够按圆的面积比较两个圆的大小。自编main函数完成测试。 *程序输入: *程序输出: */ #include <iostream> #include<cmath> using namespace std; //定义点类 class Point { public: Point(double xx=0,double yy=0):x(xx),y(yy) {} //点的构造函数 ~Point() {} double get_x() //下文要对原点的x进行操作,所以设定函数把x,y取出来 { return x; } double get_y() { return y; } friend ostream &operator<<(ostream &,const Point &); //重载输出运算符 protected: double x; double y; }; ostream &operator<<(ostream & out,const Point &p) //重载输出运算符 { out<<"("<<p.x<<","<<p.y<<")"<<endl; return out; } //由Point类派生出一个Circle(圆)类 class Circle:public Point { public: Circle(double xx=0,double yy=0,double rr=0):Point(xx,yy),r(rr) {} //圆的构造函数 ~Circle() {} friend ostream &operator<<(ostream &,const Circle &); //重载圆的输出运算符 friend int locate(Point p,Circle c); //判断点p与圆的位置关系(返回值<0圆内,==0圆上,>0 圆外) //下面进行关系运算符的重载,比较圆的面积大小 bool operator>(const Circle &); bool operator<(const Circle &); bool operator>=(const Circle &); bool operator<=(const Circle &); bool operator==(const Circle &); bool operator!=(const Circle &); private: double r; }; ostream &operator<<(ostream &out,const Circle &c) //重载圆的输出运算符 { out<<"原点O:("<<c.x<<", "<<c.y<<"),半径r="<<c.r<<endl; return out; } int locate(Point p,Circle c) //判断点p与圆的位置关系(返回值<0圆内,==0圆上,>0 圆外) { double x1=c.get_x(); double y1=c.get_y(); double dx=c.x-x1,dy=c.y-y1; double d=sqrt(dx*dx+dy*dy); if(abs(d-c.r)<1e-5) return 0; //圆上 else if (d<c.r) return -1; //圆内 else return 1; //圆外 } //下面进行关系运算符的重载,比较圆的面积大小 bool Circle::operator>(const Circle &c) { return (this->r>c.r); } bool Circle::operator<(const Circle &c) { return (this->r<c.r); } 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-5; } bool Circle::operator!=(const Circle &c) { return abs(this->r-c.r)>1e-5; } //圆的面积比较的测试函数 int main( ) { Circle c1(3,2,5),c2(4,5,5); cout<<"圆O1:"<<c1<<"圆O2:"<<c2; if(c1>c2) cout<<"O1>O2"<<endl; if(c1<c2) cout<<"O1<O2"<<endl; if(c1==c2) cout<<"O1=O2"<<endl; if(c1>=c2) cout<<"O1>=O2"<<endl; if(c1<=c2) cout<<"O1<=O2"<<endl; if(c1!=c2) cout<<"O1!=O2"<<endl; Circle c3(3,2,4),c4(4,5,5); cout<<"圆O3:"<<c3<<"圆O4:"<<c4; if(c3>c4) cout<<"O3>O4"<<endl; if(c3<c4) cout<<"O3<O4"<<endl; if(c3==c4) cout<<"O3=O4"<<endl; if(c3>=c4) cout<<"O3>=O4"<<endl; if(c3<=c4) cout<<"O3<=O4"<<endl; if(c3!=c4) cout<<"O3!=O4"<<endl; return 0; }
运行结果:
知识点总结:
圆的面积比较。
牵扯到浮点型变量的比较,尤其是相等的比较。一定要注意精度问题。
时间: 2024-11-07 02:37:12