PTA编程题 7-2 复数类模板
编写复数模板Complex,其数据成员real、img未知类型,定义相应的成员函数(构造函数, 运算符重载函数和输出函数),在主函数中实例化数据成员real、img均为double并测试复数对象。
输入格式: 输入两行:
第一行是复数x的实部和虚部,用空间分隔;
第二行是复数y的实部和虚部,用空间分隔。
输出格式: x与y之和。
输入样例: 以下是一组输入。
3.6 2.8 12.6 7.8 输出样例: 这里给出相应的输出。
(16.2, 10.6) 这里我没有自己写,而是借鉴了某个求助帖的错误代码。修改优化后,如下
#include <iostream> using namespace std; template <class ElemType> class Complex {
private: ElemType real; ElemType image; public: Complex(ElemType r = 0, ElemType i = 0) : real(r), image(i) {
}; void Show() const; Complex Add(const Complex& z2); }; template <class ElemType> void Complex<ElemType>::Show() const {
cout << "(" << real << ", " << image << ")"; } template <class ElemType> Complex<EleType> Complex<ElemType>::Add(const Complex& z2)
{
float r, i;
r = this->real + z2.real;
i = this->image + z2.image;
Complex z(r, i);
return z;
}
int main()
{
float x1=0, x2=0, y1=0, y2=0;
cin >> x1 >> y1;
cin >> x2 >> y2;
Complex<float> z1(x1, y1), z2(x2, y2);
(z1.Add(z2)).Show();
return 0;
}