问题及代码:
运行结果:
运算符重载。
/*
*Copyright (c)2015,烟台大学计算机与控制工程学院
*All rights reserved.
*文件名称:Circle.cpp
*作 者:单昕昕
*完成日期:2015年5月23日
*版 本 号:v1.0
*问题描述:
(1)先建立一个Point(点)类,包含数据成员x,y(坐标点);
(2)以Point为基类,派生出一个Circle(圆)类,增加数据成员(半径),基类的成员表示圆心;
(3)编写上述两类中的构造、析构函数及必要运算符重载函数(本项目主要是输入输出);
(4)在圆类上重载关系运算符(6种),使之能够按圆的面积比较两个圆的大小。自编main函数完成测试。
*程序输入:无。
*程序输出:按圆的面积比较两个圆的大小。
*/
#include <iostream>
#include <cmath>
using namespace std;
const double PI=acos(-1.0);
class Circle;
class Point
{
protected:
double x,y;
public:
Point(int xx=0,int yy=0):x(xx),y(yy) {}
friend ostream& operator<<(ostream&output,const Point &c);
};
ostream& operator<<(ostream&output,const Point &c)
{
output<<"("<<c.x<<","<<c.y<<")";
return output;
}
class Circle:public Point
{
protected:
double r;
public:
Circle(int xx=0,int yy=0,double rr=0):Point(xx,yy),r(rr) {};
friend ostream& operator<<(ostream&output,const 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);
double area(Circle &);
};
double Circle::area(Circle &c)
{
return PI*c.r*c.r;
}
ostream& operator<<(ostream&output,const Circle &c)
{
output<<"("<<c.x<<","<<c.y<<","<<c.r<<")";
return output;
}
bool Circle::operator > (Circle &c)
{
if (area(*this)>area(c))
return true;
else
return false;
}
bool Circle::operator < (Circle &c)
{
if (area(*this)<area(c))
return true;
else
return false;
}
bool Circle::operator >= (Circle &c)
{
if (area(*this)>=area(c))
return true;
else
return false;
}
bool Circle::operator <= (Circle &c)
{
if (area(*this)<=area(c))
return true;
else
return false;
}
bool Circle::operator == (Circle &c)
{
if (area(*this)==area(c))
return true;
else
return false;
}
bool Circle::operator != (Circle &c)
{
if (area(*this)==area(c))
return false;
else
return true;
}
int main( )
{
Circle c1(3,2,4),c2(4,5,5); //c2应该大于c1
cout<<"圆c1: "<<c1<<"的面积="<<c1.area(c1)<<endl;
cout<<"圆c2: "<<c2<<"的面积="<<c2.area(c2)<<endl;
cout<<"下面比较两个圆面积的大小:"<<endl;
if (c1>c2) cout<<"c1>c2"<<endl;
if (c1<c2) cout<<"c1<c2"<<endl;
if (c1>=c2) cout<<"c1≥c2"<<endl;
if (c1<=c2) cout<<"c1≤c2"<<endl;
if (c1==c2) cout<<"c1=c2"<<endl;
if (c1!=c2) cout<<"c1≠c2"<<endl;
return 0;
}
运行结果:
运算符重载。
学习心得:
就是又复习了一遍运算符重载。。