/*
*程序的版权和版本声明部分:
*Copyright(c)2013,烟台大学计算机学院学生
*All rights reserved.
*文件名称:复数类--重载运算符2+
*作者:刘中林
*完成日期:2014年6月10日
*版本号:v0.1
*对任务及求解方法的描述部分:
*输入描述:初始化的实数和虚数
*问题描述:定义一个复数类Complex,重载运算符“+”,使之能用于复数的加法运算。参加运算的两个运算量可以都是类对象,也可以其中有一个是整数,顺序任意。例 如,c1+c2,i+c1,c1+i均合法(设i为整数,c1,c2为复数)。编写程序,分别求两个复数之和、整数和复数之和。*程序输入:规定的初始化实数和虚数
*程序输出:计算后的结果
*问题分析:无
*算法设计:虚数的加减乘除
*我的程序:
*/
#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 &c2);
Complex operator+(int &i);
friend Complex operator+(int&,Complex &);
void display();
private:
double real;
double imag;
};
Complex Complex::operator+(Complex &c2)
{
Complex c;
c.real=c2.real+real;
c.imag=c2.imag+imag;
return c;
}
Complex Complex::operator+(int &i)
{
Complex c;
c.real=real+i;
c.imag=imag;
return c;
}
Complex operator+(int &j,Complex &c2)
{
return Complex(c2.real+j,c2.imag);
}
void Complex::display()
{
cout<<"("<<real<<","<<imag<<"i)"<<endl;
}
int main()
{
double real,imag;
cin>>real>>imag;
Complex c1(real,imag);
cin>>real>>imag;
Complex c2(real,imag);
cout<<setiosflags(ios::fixed);
cout<<setprecision(2);
Complex c3=c1+c2;
cout<<"c1+c2=";
c3.display();
int i;
cin>>real>>imag;
cin>>i;
c3=Complex(real,imag)+i;
cout<<"c1+i=";
c3.display();
cin>>i;
cin>>real>>imag;
c1=Complex(real,imag);
c3=i+c1;
cout<<"i+c1=";
c3.display();
return 0;
}
*样例输出:
*心得体会:加油啦少年,一年两次的海澜之家之旅就要开始了。。