问题及代码:
/*
*Copyright (c)2014,烟台大学计算机与控制工程学院
*All rights reserved.
*文件名称:Project.cpp
*作 者:chenqin.
*完成日期:2015年5月28日
*版 本 号:v1.0
*
*问题描述:在圆类上重载关系运算符(6种),使之能够按圆的面积比较两个圆的大小。自编main函数完成测试。
*程序输入:略
*程序输出:略
*/
#include <iostream>
#include <cmath>
using namespace std;
class Point
{
public:
Point(double xx=0,double yy=0);
~Point();
double distance(Point &p);
friend ostream& operator<<(ostream &output,Point &p);
protected:
double x,y;
};
Point::Point(double xx,double yy):x(xx),y(yy) {}
Point::~Point() {}
double Point::distance(Point &p)
{
double dx=x-p.x;
double dy=y-p.y;
return sqrt(dx*dx+dy*dy);
}
ostream& operator<<(ostream &output,Point &p)
{
output<<"("<<p.x<<","<<p.y<<")"<<endl;
return output;
}
class Circle:public Point
{
public:
Circle(double xx=0,double yy=0,double r=0);
~Circle();
double area();
friend ostream& operator<<(ostream &output,Circle &c);
bool operator<(Circle &c);
bool operator>(Circle &c);
bool operator=(Circle &c);
bool operator<=(Circle &c);
bool operator>=(Circle &c);
bool operator!=(Circle &c);
protected:
double rad;
};
Circle::Circle(double xx,double yy,double r):Point(xx,yy),rad(r) {}
Circle::~Circle() {}
double Circle::area()
{
return 3.14*rad*rad;
}
ostream& operator<<(ostream &output,Circle &c)
{
output<<"圆心"<<"("<<c.x<<","<<c.y<<") r="<<c.rad;
return output;
}
bool Circle::operator<(Circle &c)
{
if(rad-c.rad<0)
return true;
else
return false;
}
bool Circle::operator>(Circle &c)
{
if(rad-c.rad>0)
return true;
else
return false;
}
bool Circle::operator=(Circle &c)
{
if(rad-c.rad==0)
return true;
else
return false;
}
bool Circle::operator<=(Circle &c)
{
if(!(*this>c))
return true;
else
return false;
}
bool Circle::operator>=(Circle &c)
{
if(!(*this<c))
return true;
else
return false;
}
bool Circle::operator!=(Circle &c)
{
if(!(*this=c))
return true;
else
return false;
}
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;
}
运行结果:
学习心得:换汤不换药,多重复几遍对这些知识点又有了更多深刻记忆。