復數類Complex有兩個數據成員:a和b, 分別代表復數的實部和虛部,並有若干構造函數和一個重載-(減號,用於計算兩個復數的距離)的成員函數。 要求設計一個函數模板
template < class T >
double dist(T a, T b)
對int,float,Complex或者其他類型的數據,返回兩個數據的間距。
以上類名和函數模板的形式,均須按照題目要求,不得修改
1 #include<iostream> 2 #include<cmath> 3 using namespace std; 4 5 class Complex 6 { 7 private: 8 double a, b; 9 public: 10 Complex() 11 { 12 a = 0, b = 0; 13 } 14 Complex(double A, double B) 15 { 16 a = A, b = B; 17 } 18 void set(double A, double B) 19 { 20 a = A, b = B; 21 } 22 void display() 23 { 24 cout << a << " " << b << endl; 25 } 26 friend double operator - (Complex C1, Complex C2); 27 }; 28 29 double operator -(Complex C1, Complex C2) 30 { 31 return sqrt(pow(C1.a - C2.a, 2.0) + pow(C1.b - C2.b, 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 Complex a, b; 61 double a1, a2, b1, b2; 62 cin >> a1 >> a2 >> b1 >> b2; 63 a.set(a1, a2), b.set(b1, b2); 64 cout << dist(a, b) << endl; 65 } 66 } 67 68 return 0; 69 }