复数四则运算--类模板实现

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值