问题及代码:
01./* 02.*Copyright (c) 2014,烟台大学计算机学院 03.*All rights reserved. 04.*文件名称:lily.cpp 05.*作者:李莉 06.*完成日期:2015年5月24日 07.*版本号:v1.0 08.*问题描述:【项目4 - 点、圆的关系】 (1)先建立一个Point(点)类,包含数据成员x,y(坐标点); (2)以Point为基类,派生出一个Circle(圆)类,增加数据成员(半径),基类的成员表示圆心; (3)编写上述两类中的构造、析构函数及必要运算符重载函数(本项目主要是输入输出); (4)定义友元函数int locate,判断点p与圆的位置关系(返回值<0圆内,==0圆上,>0 圆外); *程序输入:无输入 *程序输出:运行结果 */ #include <iostream> #include <cmath> using namespace std; class Point { public: Point(double a=0,double b=0):x(a),y(b) {}; double distance(const Point &p)const; friend ostream&operator<<(ostream &,const Point &p); protected: double x,y; }; double Point::distance(const Point &p)const { double dx=x-p.x; double dy=y-p.y; return sqrt(dx*dx+dy*dy); } ostream &operator<<(ostream &output,const Point &p) { output<<"["<<p.x<<","<<p.y<<"]"<<endl; return output; } class Circle:public Point { public: Circle(double a=0,double b=0,double r=0):Point(a,b),radius(r) {} friend int locate(const Point &p,const Circle &c); friend ostream&operator<<(ostream&output,const Circle &c); protected: double radius; }; int locate(const Point &p,const Circle &c) { const Point cp(c.x,c.y); //圆心 double d = cp.distance(p); if (abs(d - c.radius) < 1e-7) return 0; //相等 else if (d < c.radius) return -1; //圆内 else return 1; } ostream &operator<<(ostream &output,const Circle &c) { output<<"Center=["<<c.x<<", "<<c.y<<"], r="<<c.radius<<endl; return output; } 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; return 0; }
运行结果:
心得体会:
在处理的时候又把判断位置关系的函数忘记定义成友元函数。。结果悲剧了