面向对象——案例练习(4)判断点是否在圆的内部
在一个文件里进行实现:
#define _CRT_SECURE_NO_WARNINGS #include <iostream> using namespace std; //点类 class Point { public: void setXY(int x, int y) { m_x = x; m_y = y; } int getX() { return m_x; } int getY() { return m_y; } private: int m_x; int m_y; }; //圆类 class Circle { public: void setR(int r) { m_r = r; } void setXY(int x, int y) { m_x = x; m_y = y; } //判断点是否在圆内,true表示在圆内,false表示在圆外 bool judgeCircle(Point &p) { int dd; dd = (p.getX() - m_x)*(p.getX() - m_x) + (p.getY() - m_y)*(p.getY() - m_y); if (dd > m_r*m_r) return false; else return true; } private: int m_r; int m_x; int m_y; }; int main(void) { Circle c; c.setXY(2, 2); c.setR(4); Point p; p.setXY(1, 1); if (c.judgeCircle(p) == true) { cout << "在圆的内部" << endl; } else { cout << "在圆的外部" << endl; } return 0; }
在多个文件里进行实现:
//MyPoint.h #pragma once class MyPoint { public: void setXY(int x, int y); int getY(); int getX(); private: int m_x; int m_y; };
//MyPoint.cpp #include "MyPoint.h" void MyPoint::setXY(int x, int y) { m_x = x; m_y = y; } int MyPoint::getX() { return m_x; } int MyPoint::getY() { return m_y; }
//MyCircle.h #pragma once #include "MyPoint.h" class MyCircle { public: void setR(int r); void setXY(int x, int y); bool judgePoint(MyPoint &p); private: int m_r; int m_x; int m_y; };
//MyCircle.cpp #include "MyCircle.h" #include "MyPoint.h" void MyCircle::setR(int r) { m_r = r; } void MyCircle::setXY(int x, int y) { m_x = x; m_y = y; } //判断点是否在圆内,true表示在圆内,false表示在圆外 bool MyCircle::judgePoint(MyPoint &p) { int dd; dd = (p.getX() - m_x)*(p.getX() - m_x) + (p.getY() - m_y)*(p.getY() - m_y); if (dd > m_r*m_r) return false; else return true; }
//main #define _CRT_SECURE_NO_WARNINGS #include <iostream> #include "MyCircle.h" #include "MyPoint.h" using namespace std; int main(void) { MyCircle c; c.setXY(2, 2); c.setR(4); MyPoint p; p.setXY(6, 6); if (c.judgePoint(p) == true) { cout << "在圆的内部" << endl; } else { cout << "在圆的外部" << endl; } return 0; }