码迷,mamicode.com
首页 > 其他好文 > 详细

第十二周(点圆类)

时间:2015-05-27 14:02:31      阅读:115      评论:0      收藏:0      [点我收藏+]

标签:c++ 生活

/*
*copyright(c) 2015,烟台大学计算机学院
*All rights reserved。
*文件名称:第十二周(点圆类)

*作者:王忠
*完成日期:2015.5.27

*版本号:v1.0
*
*问题描述:(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():x(0),y(0) {};
    Point(double x0, double y0):x(x0), y(y0) {};
    friend ostream& operator <<(ostream &output,Point &p);
    double distance(Point &p);
protected:
    double x,y;   //点的横坐标和纵坐标
};
class Circle:public Point
{
public:
    Circle(double x,double y,double z):Point(x,y),r(z) {}
    friend istream& operator >>(istream &input,Circle &c);
    friend ostream& operator <<(ostream &output,Circle &c);
    friend int locate(Point &p, Circle &c);
protected:
    double r;
};
ostream& operator <<(ostream &output,Point &p)
{
    output<<"Point: ("<<p.x<<","<<p.y<<")"<<endl;
    return output;
}
double Point::distance(Point &p)
{
    double dx = x-p.x;
    double dy = y-p.y;
    return sqrt(dx*dx+dy*dy);
}

istream& operator >>(istream &input,Circle &c)
{
    double a,b,d;
    cout<<"输入半径,圆心坐标:";
    input>>a>>b>>d;
    Circle(a,b,d);
    return input;
}
ostream& operator <<(ostream &output,Circle &c)
{
    output<<"Circle: ("<<c.r<<","<<c.x<<","<<c.y<<")"<<endl;
    return output;
}
int locate(Point &p,Circle &c)
{
    Point cp(c.x,c.y);
    double d = cp.distance(p);
    if (d==c.r)
        return 0;
    else if (d < c.r)
        return -1;
    else
        return 1;
}

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;
}
技术分享

第十二周(点圆类)

标签:c++ 生活

原文地址:http://blog.csdn.net/wangzhongwangmin/article/details/46045071

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!