定義一個複數類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();
- }