2017final函數模板

數據的間距問題(函數模板) 類point有三個數據成員:x、y和z, 分別表明x座標、y座標和z座標,並有若干構造函數和一個重載-(減號,計算兩點距離)的成員函數。 要求設計一個函數模板,ios

template < class T> double dist(T a, T b)函數

對int,float,point或者其餘類型的數據,返回間距。spa

 1 #include<iostream>
 2 #include<cmath>
 3 using namespace std;  4 
 5 class Point  6 {  7 private:  8     double x, y, z;  9 public: 10  Point() 11  { 12         x = 0, y = 0, z = 0; 13  } 14     Point(int xx, int yy, int zz): x(xx), y(yy), z(zz) {} 15     void set(int xx, int yy, int zz) 16  { 17         x = xx, y = yy, z = zz; 18  } 19     friend istream& operator >> (istream &input, Point &P); 20     friend double operator - (Point P1, Point P2); 21 }; 22 
23 istream& operator >> (istream &input, Point &P) 24 { 25     input >> P.x >> P.y >> P.z; 26     return input; 27 } 28 
29 double operator - (Point P1, Point P2) 30 { 31     return sqrt(pow(P1.x - P2.x, 2.0) + pow(P1.y - P2.y, 2.0) + pow(P1.z - P2.z, 2.0)); 32 } 33 
34 template<class T>
35 double dist(T a, T b) 36 { 37     return abs(a - b); 38 } 39 
40 int main() 41 { 42     int flag; 43 
44     while(cin >> flag, flag != 0) 45  { 46         if(flag == 1) 47  { 48             int a, b; 49             cin >> a >> b; 50             cout << dist(a, b) << endl; 51  } 52         else if(flag == 2) 53  { 54             float a, b; 55             cin >> a >> b; 56             cout << dist(a, b) << endl; 57  } 58         else if(flag == 3) 59  { 60  Point a, b; 61             cin >> a >> b; 62             cout << dist(a, b) << endl; 63  } 64  } 65 
66     return 0; 67 }
相關文章
相關標籤/搜索