定义一个复数类Complex,重载运算符“+”,使之能用于复数的加法运算。参加运算的两个运算符可以都是类对象。也可以其中一个是整数,顺序任意。例如:c1+c2,i+c1,c1+i 均合法(设i为整数,c1 c2为复数)。编程序 分别求两个复数之和,整数和复数之和。
- #include<iostream>
- using namespace std;
- class Complex
- {
- public:
- Complex(){real=0;imag=0;}
- Complex(double r,double i){real=r;imag=i;}
- void display();
- double real;
- double imag;
- };
- void Complex::display()
- {
- cout<<"("<<real<<","<<imag<<"i)";
- }
- Complex operator +(Complex &c1,Complex &c2)
- {
- Complex p;
- p.real=c1.real+c2.real;
- p.imag=c1.imag+c2.imag;
- return p;
- }
- Complex operator +(Complex &c1,int c2)
- {
- Complex p;
- p.real=c1.real+c2;
- p.imag=c1.imag;
- return p;
- }
- Complex operator +(int &c1,Complex &c2)
- {
- Complex p;
- p.real=c1+c2.real;
- p.imag=c2.imag;
- return p;
- }
- int main()
- {
- Complex c1(5,2),c2(1,3),c3;
- c1.display();
- cout<<"+";
- c2.display();
- cout<<"=";
- c3=c1+c2;
- c3.display();
- cout<<endl;
- int i=10;
- c3=i+c1;
- c3.display();
- }