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;
}
  • 4
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值