在多态性实验第2题的基础上,在复数类中增加输入流运算符>>和输出流运算符<<的重载,主函数通过“cin>>对象名”输入对象的值,通过“cout<<对象名”输出对象的值,输出复数值时将原来主函数中“对象名.print( )”改成“cout<<对象名”形式。
在上一步完成的基础上,将复数类改成一个类模板,只设一个模板参数,即实部和虚部用同一种类型,修改相应的代码,完成输入、输出功能。
#include<iostream>
using namespace std;
template<class T>
class Complex
{
private:
T real;
T imag;
public:
Complex(T r = 0, T i = 0)
{
real = r;
imag = i;
}
void print()
{
cout << real;
if (imag != 0)
{
if (imag > 0)cout << "+";
cout << imag << "i";
}
cout << endl;
}
friend istream & operator >>(istream& in, Complex<T> & c)
{
in >> c.real;
in >> c.imag;
return in;
}
friend ostream & operator <<(ostream& out, Complex<T> & c)
{
out << c.real;
if (c.imag != 0)
{
if (c.imag > 0) out << "+";
out << c.imag << "i";
}
out << endl;
return out;
}
friend Complex<T> operator + (const Complex<T> &a, const Complex &b)
{
Complex c;
c.real = a.real + b.real;
c.imag = a.imag + b.imag;
return c;
}
};
int main()
{
Complex<double> a1(2.3,4.6),a2(3.6,2.8),a3;
a3 = a1 + a2;
cout << "a1="<< a1;
cout << "a2="<< a2;
cout << "a3=a1+a2="<<a3;
return 0;
}