C++源码:类的应用实例-复数
// Example for Class 类的实例
// Complex 定义 复数类
#include <iostream>
using namespace std;
class complex
{
private: //Default is private!
float r,i;
public:
complex operator+(complex c1); //Overload "+"
complex operator-(complex c2); //Overload "-"
void init(float rr,float ii);
void show(void);
};
complex complex::operator+(complex c1)
{
complex temp;
temp.r=r+c1.r;
temp.i=i+c1.i;
return temp;
}
complex complex::operator-(complex c2)
{
complex temp;
temp.r=r-c2.r;
temp.i=i-c2.i;
return temp;
}
void complex::init(float rr,float ii)
{
r=rr;
i=ii;
}
void complex::show(void)
{
if (i>=0)
cout<<"\nThe complex is:"<<r<<"+"<<i<<"i\n\n";
else
cout<<"\nThe complex is:"<<r<<"+("<<i<<")i\n\n";
}
main()
{
complex cc1,cc2,cc3,cc4;
float x=1,y=1;
while (x!=1000.0)
{
cout<<"\007"<<"Please input the real,i part vallue of COMPLEX:"<<flush;
cin>>x>>y;
// PROCESS USER WANT TO EXIT (1)
if (x==0)
{
cout<<" \n\n You want to EXIT !\n BeCAUSE YOU INPUT X=0,Y=0";
return 1;
}
cout<<"\nThe Complex CC1 YOU INPUT is:"<<x<<"+"<<y<<"i\n";
cc1.init(x,y);
cout<<"\007"<<"Please input the real,i part vallue of COMPLEX:"<<flush;
cin>>x>>y;
cout<<"\nThe Complex CC2 YOU INPUT is:"<<x<<"+"<<y<<"i\n";
cc2.init(x,y);
/* cc1.r=1.0; cc1.i=1.0;
cc2.r=2.0; cc2.i=2.0; */
/*
cc1.init(1.0,1.0); // \\
cc2.init(2.0,2.0); // \\ */
cout<<"\n After cc.init()";
cout<<"\nComplex CC1:";
cc1.show();
cout<<"\nComplex CC2:";
cc2.show();
cc3=cc1+cc2;
cc4=cc2-cc1;
/* cout<<"\nCC3="<<cc3.r<<"+"<<cc3.i<<"i\n";
cout<<"\nCC3="<<cc3.r<<"+"<<cc3.i<<"i\n"; */
cout<<"\nComplex PLUS:cc2+cc1=";
cc3.show();
cout<<"\nComplex CC2-cc1=";
cc4.show();
} //end while
return 0;
} // end main