求线段长

来源:互联网 发布:下载福州网络家长学校 编辑:程序博客网 时间:2024/06/05 16:38

这个程序是书上例题,主要是辅助理解组合类

[cpp] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. #include <iostream>  
  2. #include <cmath>  
  3.   
  4. using namespace std;  
  5.   
  6. class Point  //定义Point类  
  7. {  
  8.     public:  
  9.         Point(int xx= 0, int yy = 0)  
  10.         {  
  11.             x = xx;  
  12.             y = yy;  
  13.         }  
  14.           
  15.         Point(Point &p);  
  16.   
  17.         int getx()   
  18.         {  
  19.             return x;  
  20.         }  
  21.   
  22.         int gety()  
  23.         {  
  24.             return y;  
  25.         }  
  26.   
  27.     private:  
  28.         int x,y;  
  29. };  
  30.   
  31. Point::Point(Point &p)//复制构造函数实现  
  32. {  
  33.     x = p.x;  
  34.     y = p.y;  
  35.   
  36.     cout<<"calling the copy constructor of point"<<endl;  
  37. }  
  38. //类的组合  
  39. class Line//line类的定义  
  40. {  
  41.     public://外部接口  
  42.         Line(Point xp1,Point xp2);  
  43.         Line(Line &l);  
  44.         double getLen()  
  45.         {  
  46.             return len;  
  47.         }  
  48.   
  49.     private://私有数据成员  
  50.         Point p1,p2;//Point类的对象p1,p2  
  51.         double len;  
  52. };  
  53. //组合类的构造函数  
  54. Line::Line(Point xp1,Point xp2):p1(xp1),p2(xp2)  
  55. {  
  56.     cout<<"calling constructor of line"<<endl;  
  57.     double x = static_cast<double>(p1.getx() - p2.getx());  
  58.     double y = static_cast<double>(p1.gety() - p2.gety());  
  59.     len = sqrt(x*x + y*y);  
  60. }  
  61. //组合类的复制构造函数  
  62. Line::Line(Line &l):p1(l.p1),p2(l.p2)  
  63. {  
  64.     cout<<"calling the copy constructor of line"<<endl;  
  65.     len = l.len;  
  66. }  
  67.   
  68. int main()  
  69. {  
  70.     Point myp1(1,1),myp2(4,5);//建立Point类的对象  
  71.   
  72.     Line line(myp1,myp2);//建立Line类的对象  
  73.     Line line2(line);//利用复制构造函数建立一个新对象  
  74.     cout<<"The length of the line is:";  
  75.     cout<<line.getLen()<<endl;  
  76.     cout<<"The length of the line2 is:";  
  77.     cout<<line.getLen()<<endl;  
  78.     return 0;  
  79.   
  80.     return 0;  
  81. }  
0 0
原创粉丝点击