研究半天,没弄出来,求大神指点,谢谢!
//一个复数类Complex,重载运算符“+”使之能够完成附属的加法运算。#include "stdafx.h"
#include <iostream>
using namespace std;
class Complex
{public:
//Complex() {real=0;imag=0;}
Complex(double r=0,double i=0):real(r),imag(i) {}
Complex operator+ (Complex &c2);
friend Complex operator+ (Complex &c,int &i);
friend Complex operator+ (int &i,Complex &c2);
void display();
private:
double real;
double imag;
};
Complex Complex::operator+ (Complex &c2)
{return Complex(real+c2.real,imag+c2.imag);
}
Complex operator+(Complex &c,int &i)
{return Complex(i+c.real,c.imag);
}
Complex operator+ (int &i,Complex &c2)
{return (i+c2.real,c2.imag);
};
void Complex::display()
{cout<<'('<<real<<','<<imag<<'i)'<<endl;
}
int main ()
{Complex r1(1,2),r2(3,4),r3;
r3 = r1 + r2;
r3 = r2 + r1;
r3 = r1 + 4;
r3 = 4 + r1;
cout<<"r1=";r1.display();
cout<<"r2=";r2.display();
cout<<"r1+r2=";r3.display();
return 0;
}