PTA编程题 7-2 复数类模板
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)
这里我并没有自己写,而是借鉴了某个求助帖的有错代码,修正优化后如下 (借鉴源:https://tieba.baidu.com/p/2356316766)
#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<ElemType> 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; }