2017final函数模板
数据的间距问题(函数模板) 类point有三个数据成员:x、y和z, 分别代表x坐标、y坐标和z坐标,并有若干构造函数和一个重载-(减号,计算两点距离)的成员函数。 要求设计一个函数模板,
template < class T> double dist(T a, T b)
对int,float,point或者其他类型的数据,返回间距。
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 }