/*
*copyright (c)2015,烟台大学计算机学院
*All rights reserved
*文件名称:project.cpp
*作者:孙春红
*完成日期:2015年5月27日
*版本号:v1.0
*
*问题描述:(1)先建立一个Point(点)类,包含数据成员x,y(坐标点);
(2)以Point为基类,派生出一个Circle(圆)类,增加数据成员(半径),基类的成员表示圆心;
(3)编写上述两类中的构造、析构函数及必要运算符重载函数(本项目主要是输入输出);
(4)定义友元函数int locate,判断点p与圆的位置关系(返回值<0圆内,==0圆上,>0 圆外);
(5)在圆类上重载关系运算符(6种),使之能够按圆的面积比较两个圆的大小。自编main函数完成测试。
*输入描述:略。
*程序输出:略。
*/
#include <iostream>
#include <cmath>
using namespace std;
class Point
{
protected:
double x;
double y;
public:
double get_x()
{
return x;
}
double get_y()
{
return y;
}
Point (double a,double b):x(a),y(b) {}
friend ostream& operator<<(ostream &out,Point &p);
};
class Circle:public Point
{
private:
double radius;
public:
Circle(double a,double b,double r):Point(a,b),radius(r) {}
friend ostream& operator<<(ostream &out,Circle &c);
double get_r()
{
return radius;
}
friend int locate();
friend bool operator > (Circle &c1,Circle &c2);
friend bool operator < (Circle &c1,Circle &c2);
friend bool operator >=(Circle &c1,Circle &c2);
friend bool operator <=(Circle &c1,Circle &c2);
friend bool operator ==(Circle &c1,Circle &c2);
friend bool operator !=(Circle &c1,Circle &c2);
};
ostream& operator<<(ostream &out,Circle &c)
{
cout<<"圆心是:("<<c.get_x()<<","<<c.get_y()<<") 半径是: r="<<c.radius<<endl;
return out;
}
ostream& operator<<(ostream &out,Point &p)
{
cout<<"("<<p.x<<","<<p.y<<")"<<endl;
return out;
}
int locate(Point p,Circle c)
{
double d;
d=sqrt((p.get_x()-c.get_x())*(p.get_x()-c.get_x())+(p.get_y()-c.get_y())*(p.get_y()-c.get_y()));
return (d-c.get_r());
}
bool operator > (Circle &c1,Circle &c2)
{
if (c1.get_r()>c2.get_r())
return true;
return false;
}
bool operator < (Circle &c1,Circle &c2)
{
if (c1.get_r()<c2.get_r())
return true;
return false;
}
bool operator == (Circle &c1,Circle &c2)
{
if (c1.get_r()==c2.get_r())
return true;
return false;
}
bool operator >=(Circle &c1,Circle &c2)
{
if (c1.get_r()<c2.get_r())
return false;
return true;
}
bool operator <=(Circle &c1,Circle &c2)
{
if (c1.get_r()>c2.get_r())
return false;
return true;
}
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;
if (c1>c2)
cout<<"c1>c2"<<endl;
if (c1<c2)
cout<<"c1<c2"<<endl;
if (c1==c2)
cout<<"c1=c2"<<endl;
return 0;
}
运行结果:
知识点总结:
友元函数的应用,以及以前所学的的多种运算符重载。