5.封装设计案例分文件编写

2021-01-27  本文已影响0人  lxr_

点和圆的关系
1.point.h

#pragma once//防止头文件重复包含
#include<iostream>
using namespace std;
class Point
{
public:
    void setX(int x);
    
    int getX();
    
    void setY(int y);
    
    int getY();
    
private:
    int m_X;
    int m_Y;
};

2.circle.h

#pragma once
#include<iostream>
using namespace std;
#include "point.h"

class circle
{
public:
void setR(int r);

int getR();

void setCenter(Point center);

Point getCenter();
        

//判断点和圆的关系
void isInCircle(circle c, Point p);
    
private:
    int m_R;//半径
    Point m_Center;//圆心
};

3.point.cpp

#include "point.h"

void Point::setX(int x)
{
    m_X = x;
}
int Point::getX()
{
    return m_X;
}
void Point::setY(int y)
{
    m_Y = y;
}
int Point::getY()
{
    return m_Y;
}

4.circle.cpp

#include "circle.h"


void circle::setR(int r)
{
    m_R = r;
}
int circle::getR()
{
    return m_R;
}
void circle::setCenter(Point center)
{
    m_Center = center;
}
Point circle::getCenter()
{
    return m_Center;
}
//判断点和圆的关系
void circle::isInCircle(circle c, Point p)
{
        //圆心与点之间的距离的平方
    int distance = (c.getCenter().getX() - p.getX()) * 
                   (c.getCenter().getX() - p.getX()) +
                   (c.getCenter().getY() - p.getY()) * 
                   (c.getCenter().getY() - p.getY());
    if (distance > c.getR() * c.getR())
        cout << "点在圆外" << endl;
    else if (distance < c.getR() * c.getR())
        cout << "点在圆内" << endl;
    else
        cout << "点在圆上" << endl;
}

6.main.cpp

//点和圆的关系
#include<iostream>
using namespace std;
#include"point.h"
#include"circle.h"
//采用分文件编写,注释掉此部分
/*
class Point
{
public:
    void setX(int x)
    {
        m_X = x;
    }
    int getX()
    {
        return m_X;
    }
    void setY(int y)
    {
        m_Y = y;
    }
    int getY()
    {
        return m_Y;
    }
private:
    int m_X;
    int m_Y;
};
*/
/*
class circle
{
public:
    void setR(int r)
    {
        m_R = r;
    }
    int getR()
    {
        return m_R;
    }
    void setCenter(Point center)
    {
        m_Center = center;
    }
    Point getCenter()
    {
        return m_Center;
    }
    //判断点和圆的关系
    void isInCircle(circle c, Point p)
    {
        int distance = (c.getCenter().getX() - p.getX()) * (c.getCenter().getX() - p.getX()) +
            (c.getCenter().getY() - p.getY()) * (c.getCenter().getY() - p.getY());
        if (distance > c.getR() * c.getR())
            cout << "点在圆外" << endl;
        else if(distance < c.getR() * c.getR())
            cout << "点在圆内" << endl;
        else
            cout << "点在圆上" << endl;
    }
private:
    int m_R;
    Point m_Center;//一个类可以作为另一个类的成员
};
*/
int main()
{
    //实例化圆
    circle c;
    c.setR(10);
    Point center;
    center.setX(0);
    center.setY(0);
    c.setCenter(center);
    //实例化点
    Point p;
    p.setX(10);
    p.setY(0);
    //判断关系
    c.isInCircle(c, p);
    system("pause");
    return 0;
}
上一篇下一篇

猜你喜欢

热点阅读