定义一个复数类Complex,重载运算符“+”,使之能用于复数的加法运算与输出操作。 (1)参加运算的两个运算量可以都是类对象,也可以其中有一个是实数,顺序任意。例如,c1+c2,d+c1,c1+d均

#include <iostream>
#include <iomanip>
using namespace std;

class Complex
{
public:
Complex():real(0),imag(0) {}
Complex(double r,double i):real(r),imag(i) {}
Complex operator+(Complex &);
Complex operator+(double &);
friend Complex operator+(double&,Complex &);
friend ostream& operator << (ostream& output, const Complex& c);
private:
double real;
double imag;
};

//将程序需要的其他成份写在下面,只提交begin到end部分的代码
//******************** begin ********************

Complex Complex ::operator+(Complex &c)
{
	Complex temp(real+c.real,imag+c.imag);
	return temp;
}

Complex Complex ::operator+(double &d)
{
	return Complex(real+d,imag);
}

Complex operator+(double& d,Complex &c)
{
	return Complex(d+c.real,c.imag);
}

ostream& operator<<(eostram &cout,const Complex &c)
{
	/*
	重载<< 函数返回类型是一个流的引用, 第一个参数是流,第二个参数是以引用传递的方式的一个类的实例(并且只能对这个参数读操作)
	*/

	/*
	第二个形参,也就是右操作数,在这里传值的话会调用到Complex类的复制构造函数,
	出于效率的考虑,将它设定为传引用。因为<<操作符一般不更改右操作数的内容,所以将它定义为const。
    所以第二个形参应该是const Complex&
	*/


	/*
	setiosflags 意思就是设置输入输出的标志
	iso::fixed 是操作符setiosflags 的参数之一,该参数指定的动作是以带小数点的形式表示浮点数,
	并且在允许的精度范围内尽可能的把数字移向小数点右侧;
	ios::right是 右对齐
	setprecision(2)是设置数字的精度为2
	*/

    cout<<setiosflags(ios::fixed);   
	cout<<setprecision(2);
	cout<<'('<<c.real;
	if(c.imag>0)
		cout<<'+';
	cout<<c.imag<<"i)"<<endl;
}

//********************* end ********************
int main()
{
//测试复数加复数
double real,imag;
cin>>real>>imag;
Complex c1(real,imag);
cin>>real>>imag;
Complex c2(real,imag);
Complex c3=c1+c2;
cout<<"c1+c2=";
cout<<c3;

//测试复数加实数
double d;
cin>>real>>imag;
cin>>d;
c3=Complex(real,imag)+d;
cout<<"c1+d=";
cout<<c3;

//测试实数加复数
cin>>d;
cin>>real>>imag;
c1=Complex(real,imag);
c3=d+c1;
cout<<"d+c1=";
cout<<c3;

return 0;
}

 

  • 3
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值