定义一个复数类Complex,重载运算符“+”,使之能用于复数的加法运算。
的有关信息介绍如下:代码为:
#include <iostream> //用VC++时改为∶ #include <iostream.h>
using namespace std; //用VC++时为取消此行
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 &c)
{return Complex(real+c.real,imag+c.imag);}
Complex Complex::operator+(int &i)
{return Complex(real+i,imag);}
void Complex::display()
{cout<<"("<<real<<","<<imag<<"i)"<<endl;}
Complex operator+(int &i,Complex &c)
{return Complex(i+c.real,c.imag);}
int main()
{Complex c1(3,4),c2(5,-10),c3;
int i=5;
c3=c1+c2;
cout<<"c1+c2=";
c3.display();
c3=i+c1;
cout<<"i+c1=";
c3.display();
c3=c1+i;
cout<<"c1+i=";
c3.display();
return 0;
}
注意事项
可以用下列结构描述复数信息;
struct complex
{
int real;
int image;
};
试写出两个通用函数,分别用来求两复数的和与积。其函数原型分别为:
struct complex add(struct complex c1,struct complex c2);
即参数和返回值用结构变量。
输入:
输入数据有若干行。每行上有四个整数,前两个表示一个复数的实部和虚部,后两个表示另一个复数的实部和虚部。