定义一个复数类Complex,重载运算符"+".使之能用于复数的加法运算,将运算符函数重载为非成员、非友员的普通函数。编写程序求2个复数之和。ios
- #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;
- }
- int main()
- {
- Complex c1(5,2),c2(1,3),c3;
- c1.display();
- cout<<"+";
- c2.display();
- cout<<"=";
- c3=c1+c2;
- c3.display();
- }