C++基础编程题(39)“定义一个复数类Complex,重载运算符“+”,使之能用于复数的加法运算。参加运算的两个运算符可以都是类对象。也可以其中一个是整数,顺序任意。例如:c1+c2,i+c1,c1+i
#include
using namespace std;
class Complex
{
public:
Complex(){real=0;image=0;}
Complex(int r){real=r;image=0;}
Complex(double r,double i){real=r;image=i;}
double get_real(){return real;}
void set_real(double r){real=r;}
double get_image(){return image;}
void set_image(double i){image=i;}
void display(){cout<<”(“<<real<<”,”<<image<<”)”<<endl;}
friend Complex operator +(Complex c1,Complex c2);
private:
double real;
double image;
};
Complex operator +(Complex c1,Complex c2)
{
return Complex(c1.get_real()+c2.get_real(),c1.get_image()+c2.get_image());
}
int main()
{
Complex c1(1,1),c2(2,2),c3;
int i=2;
cout<<”c1=”;c1.display();
cout<<”c2=”;c2.display();
cout<<”i=”<c3 = c1+i;
cout<<"c1+i=";c3.display();cout;
c3 = c1+c2
cout<<"c1+c2=";c3.display();cout;
system("pause");
return 0;
}