2015-第5周项目1-体验常成员函数

来源:互联网 发布:苏打饼干 知乎 编辑:程序博客网 时间:2024/06/01 09:17

【项目1-体验常成员函数】
设计平面坐标点类,计算两点之间距离、到原点距离、关于坐标轴和原点的对称点等。在设计中,由于求距离、求对称点等操作对原对象不能造成任何改变,所以,将这些函数设计为常成员函数是合适的,能够避免数据成员被无意更改。

[cpp] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. class CPoint  
  2. {  
  3. private:  
  4.   double x;  // 横坐标  
  5.   double y;  // 纵坐标  
  6. public:  
  7.   CPoint(double xx=0,double yy=0);  
  8.   double Distance1(CPoint p) const//两点之间的距离(一点是当前点——想到this了吗?,另一点为p)  
  9.   double Distance0() const;          // 到原点(0,0)的距离  
  10.   CPoint SymmetricAxis(char style) const;//style取'x','y'和'o'分别表示按x轴, y轴, 原点对称  
  11.   void input();  //以x,y 形式输入坐标点  
  12.   void output(); //以(x,y) 形式输出坐标点  
  13. };  



代码:
#include <iostream>#include <cmath>using namespace std;class CPoint{private:    double x;  // 横坐标    double y;  // 纵坐标public:    CPoint(double xx=0,double yy=0);    double Distance1(CPoint p) const; //两点之间的距离(一点是当前点——想到this了吗?,另一点为p)    double Distance0() const;          // 到原点(0,0)的距离    CPoint SymmetricAxis(char style) const;//style取'x','y'和'o'分别表示按x轴, y轴, 原点对称    void input();  //以x,y 形式输入坐标点    void output(); //以(x,y) 形式输出坐标点};CPoint::CPoint(double xx,double yy){    x=xx;    y=yy;}double CPoint::Distance1(CPoint p) const          double a;    a=(x-p.x)*(x-p.x)+(y-p.y)*(y-p.y);    return sqrt(a);}double CPoint::Distance0() const              {    double a;    a=x*x+y*y;    return sqrt(a);}CPoint CPoint::SymmetricAxis(char style) const{    CPoint n;    switch(style)    {    case'x':    {        n.x=x;        n.y=-y;    }    break;    case'y':    {        n.x=-x;        n.y=y;    }    break;    case'o':    {        n.x=-x;        n.y=-y;    }    break;    }    return n;}void CPoint::input()                  {    char a;    cout<<"请输入坐标点(格式x,y ):";    while(1)    {        cin>>x>>a>>y;        if (a==',') break;        cout<<"Input error!\n";    }}void CPoint::output(){    cout<<"("<<x<<","<<y<<")";}int main(){    CPoint a,b,c;    cout<<"请输入a点的坐标:";    a.input();    cout<<"请输入b点的坐标:";    b.input();    cout<<"a到原点的距离为:";    cout<<a.Distance0();    cout<<"\na到b点的距离为:";    cout<<a.Distance1(b);    cout<<"\na关于x轴的对称点为:";    c=a.SymmetricAxis('x');    c.output();    cout<<"\na关于y轴的对称点为:";    c=a.SymmetricAxis('y');    c.output();    cout<<"\na关于原点的对称点为:";    c=a.SymmetricAxis('o');    c.output();    return 0;}


运行结果:






0 0