#include<iostream>
using namespace std;
template<class numtype>
class Complex {
public:
Complex(numtype a=0, numtype b=0) :x(a), y(b) {}
Complex complex_add(Complex &);
Complex complex_sub(Complex &);
Complex complex_mul(Complex &);
Complex complex_div(Complex &);
void display();
private:
numtype x, y;
};
//每一个成员函数的定义前,必须要声明类模板
//使用了模板的类,将不再独立使用,其类名的完整表示为“类模板名<虚拟类型参数>”
//凡用到类名处也用“类模板名<虚拟类型参数>”形式;
template<class numtype>
Complex<numtype> Complex<numtype>::complex_add(Complex<numtype> &c) {
Complex<numtype> nc;
nc.x = x + c.x;
nc.y = y + c.y;
return nc;
}
template<class numtype>
Complex<numtype> Complex<numtype>::complex_sub(Complex<numtype> &c) {
Complex<numtype> nc;
nc.x = x - c.x;
nc.y = y - c.y;
return nc;
}
template<class numtype>
Complex<numtype> Complex<numtype>::complex_mul(Complex<numtype> &c) {
Complex<numtype> nc;
nc.x = x*c.x-y*c.y;
nc.y = x*c.y+y*c.x;
return nc;
}
template<class numtype>
Complex<numtype> Complex<numtype>::complex_div(Complex<numtype> &c) {
Complex<numtype> nc;
nc.x = (x*c.x+y*c.y)/(c.x*c.x+c.y*c.y);
nc.y = (y*c.x - x*c.y) / (c.x*c.x + c.y*c.y);
return nc;
}
template<class numtype>
void Complex<numtype>::display() {
cout <<"("<< x <<","<<y<<"i)"<< endl;
}
int main()
{
Complex<int> c1(1, 2), c2(2, 4), c3; //实部和虚部是int型
c3 = c1.complex_add(c2);
cout << "c1+c2=";
c3.display();
c3 = c1.complex_sub(c2);
cout << "c1-c2=";
c3.display();
c3 = c1.complex_mul(c2);
cout << "c1*c2=";
c3.display();
c3 = c1.complex_div(c1);
cout << "c1/c2=";
c3.display();
return 0;
}
复数四则运算--类模板实现
最新推荐文章于 2024-07-10 15:37:26 发布