一.问题描述:
复数类Complex有两个数据成员:a和b, 分别代表复数的实部和虚部,并有若干构造函数和一个重载-(减号,用于计算两个复数的距离)的成员函数。 要求设计一个函数模板
template < class T >
double dist(T a, T b)
对int,float,Complex或者其他类型的数据,返回两个数据的间距。
以上类名和函数模板的形式,均须按照题目要求,不得修改
二.代码插入:
#include<iostream> #include<math.h> using namespace std; template < class T > double dist(T a, T b) { double distance = a - b; return fabs(distance); } class Complex { private: double real; double imag; public: Complex(double r = 0, double i = 0) { real = r; imag = i; } double operator-(Complex p) { double distance = 0; double t = (real - p.real) * (real - p.real) + (imag - p.imag) * (imag - p.imag); distance = sqrt(t); return distance; } }; int main() { int ch = 0; while (cin >> ch) { if (ch == 0) break; else if (ch == 1) { int a, b,distance; cin >> a >>b; distance=dist(a, b); cout <<distance <<endl; } else if (ch == 2) { float a, b; double distance; cin >> a >> b; distance = dist(a, b); cout << distance << endl; } else if (ch == 3) { double a, b, c, d,distance; cin >> a >> b >> c >> d; Complex p1(a, b), p2(c, d); distance = dist(p1, p2); cout << distance << endl; } } return 0; }
标签:real,distance,函数,double,imag,Complex,模板 From: https://www.cnblogs.com/lzh0416/p/17379984.html