11.1.5重学C++之【封装:案例2扩展“CirclePointClass项目”】

point.h

/*
#ifndef POINT_H_INCLUDED
#define POINT_H_INCLUDED



#endif // POINT_H_INCLUDED
*/


#pragma once
#include<iostream>
using namespace std;


class Point{
private:
    int x;
    int y;
public:
    void set_x(int _x); // 仅保留成员函数的声明,具体实现详见point.cpp
    int get_x();
    void set_y(int _y);
    int get_y();
};

point.cpp

#include "point.h"


void Point::set_x(int _x){ // 加上作用域Point::以标明是Point类的成员函数,否则默认为全局函数
    x = _x;
}
int Point::get_x(){
    return x;
}
void Point::set_y(int _y){
    y = _y;
}
int Point::get_y(){
    return y;
}

circle.h

/*
#ifndef CIRCLE_H_INCLUDED
#define CIRCLE_H_INCLUDED



#endif // CIRCLE_H_INCLUDED
*/


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


class Circle{
private:
    int r;
    Point center;
public:
    void set_r(int _r);
    int get_r();
    void set_center(Point _center);
    Point get_center();
};

circle.cpp

#include "circle.h"


void Circle::set_r(int _r){
    r = _r;
}
int Circle::get_r(){
    return r;
}
void Circle::set_center(Point _center){
    center = _center;
}
Point Circle::get_center(){
    return center;
}

test.cpp

#include<iostream>
#include<string>
#include "point.h"
#include "circle.h"
using namespace std;


void is_incircle(Circle & c, Point & p){ // 判断点和圆的关系
    // 两点之间距离=[(x1-x2)^2 + (y1-y2)^2]的开平方
    int p_distance =
    (c.get_center().get_x() - p.get_x())*(c.get_center().get_x() - p.get_x()) +
    (c.get_center().get_y() - p.get_y())*(c.get_center().get_y() - p.get_y());

    int r_distance = c.get_r() * c.get_r();

    if(p_distance == r_distance){
        cout << "点在圆上" << endl;
    }else if(p_distance > r_distance){
        cout << "点在圆外" << endl;
    }else{
        cout << "点在圆内" << endl;
    }
}


int main(){
    // 案例2 点圆关系
    Point center;
    center.set_x(10);
    center.set_y(0);
    Circle c;
    c.set_center(center);
    c.set_r(10);

    Point p;
    p.set_x(10);
    p.set_y(10);
    is_incircle(c, p); // 点在圆上
    p.set_x(10);
    p.set_y(11);
    is_incircle(c, p); // 点在圆外
    p.set_x(10);
    p.set_y(9);
    is_incircle(c, p); // 点在圆内

    return 0;
}

 

posted @ 2021-03-14 18:39  yub4by  阅读(19)  评论(0编辑  收藏  举报