上一讲提到的判断两个圆的关系,通过类实现,看代码:
#include<iostream> #include<cmath> using namespace std; //判断两个圆的关系 // 点类 class Point { public: void setXY(int x, int y) { m_x = x; m_y = y; } //计算两点间的方法 double pointDistance(Point &another) { int d_x = m_x - another.m_x; int d_y = m_y - another.m_y; double dis = sqrt(d_x*d_x + d_y*d_y); return dis; } private: int m_x; int m_y; }; class Circle { public: void setR(int r) { m_r = r; } void setXY(int x, int y) { p0.setXY(x, y); } //判断是否相交 bool isInter(Circle &another) { //两个半径只和 int rr = m_r + another.m_r; //两圆心之间的距离 double dis = p0.pointDistance(another.p0); if (dis <= rr) { //相交 return true; } else { //不相交 return false; } } private: int m_r; Point p0; }; int main(void) { Circle c1, c2; int x, y, r; cout << "请输入第一个圆的半径" << endl; cin >> r; c1.setR(r); cout << "请输入第一个圆的x" << endl; cin >> x; cout << "请输入第一个圆的y" << endl; cin >> y; c1.setXY(x, y); cout << "请输入第二个圆的半径" << endl; cin >> r; c2.setR(r); cout << "请输入第二个圆的x" << endl; cin >> x; cout << "请输入第二个圆的y" << endl; cin >> y; c2.setXY(x, y); if (c1.isInter(c2) == true) { cout << "相交" << endl; } else { cout << "不相交" << endl; } system("pause"); return 0; }首先新建一个point类
class Point { public: void setXY(int x, int y) { m_x = x; m_y = y; } //计算两点间的方法 double pointDistance(Point &another) { int d_x = m_x - another.m_x; int d_y = m_y - another.m_y; double dis = sqrt(d_x*d_x + d_y*d_y); return dis; } private: int m_x; int m_y; };设置两个私有成员变量 int m_x; int m_y; 然后定义一个 void setXY(int x, int y) { m_x = x; m_y = y; } 为了方便操作和赋值 //计算两点间的方法 double pointDistance(Point &another) { int d_x = m_x - another.m_x; int d_y = m_y - another.m_y; double dis = sqrt(d_xd_x + d_yd_y); return dis; } 这里是计算两个点的距离,并返回,另外需要注意在,在同一类中两个对象可以互相调用。
这里又定义一个圆类 class Circle { public: void setR(int r) { m_r = r; }
void setXY(int x, int y) { p0.setXY(x, y); } //判断是否相交 bool isInter(Circle &another) { //两个半径只和 int rr = m_r + another.m_r; //两圆心之间的距离 double dis = p0.pointDistance(another.p0); if (dis <= rr) { //相交 return true; } else { //不相交 return false; } }private: int m_r; Point p0; }; 圆类中设置一个私有成员变量和一个私有类(也就是上面的点类,这样两个类之间就可以进行调用了) 这里设置了圆的半径设置函数 void setR(int r) { m_r = r; } void setXY(int x, int y) { p0.setXY(x, y); } 设置点x,y,这里就是通过在circle类中的point成员变量,操作点类中的(x,y) double dis = p0.pointDistance(another.p0); if (dis <= rr) { //相交 return true; } else { //不相交 return false; } } 最后通过这个调用实现对判断 然后在主函数中进行这些函数的调用,参数设置,最后实现。 (完!)