定义一个复数类,重载运算符“+”,“-”,“++”,“>”,使之用于复数的加、减、自加并比较两个复数大小;
代码如下:
#include <iostream>
using namespace std;
class Complex
{
public:
double real;
double image;
public:
Complex(double r,double i)
{
real=r; image=i;
}
Complex(double r)
{
real=r; image=0;
}
Complex()
{
real=0; image=0;
}
Complex operator + (const Complex Right)
{
Complex temp;
temp.real = real + Right.real;
temp.image = image + Right.image;
return temp;
}
Complex operator - (const Complex Right) {
Complex temp;
temp.real = real - Right.real;
temp.image = image - Right.image;
return temp;
}
Complex operator ++(){
this->real += 1;
this->image += 1;
return *this;
}
Complex operator --(){
this->real -=1;
this->image -=1;
return *this;
}
Complex operator * (const Complex Right) {
Complex temp;
temp.real = real * Right.real - image * Right.image;
temp.image = real * Right.image + image * Right.image;
return temp;
}
Complex operator /(const Complex Right)
{
Complex temp;
temp.real=real/Right.real;
temp.image =image/Right.real;
return temp;
}
int operator ==(const Complex Right)
{
if (this->real == Right.real && this->image < Right.image)
{
return 1;
}else
return 0;
}
int operator > (const Complex Right)
{
if(this->real > Right.real)
return 1;
else if (this->real == Right.real && this->image < Right.image)
{
return 1;
}
else if (this->real == Right.real && this->image == this->image)
{
return 0;
}else
return -1;
}
friend void print(Complex comp);
};
void print(Complex comp)
{
cout<< comp.real << " + "<<comp.image << "i"<<endl;
}
int main()
{
Complex c1(3.5,5.5);
Complex c2(-3.5,1.0);
Complex t1 = c1 + c2;
print(t1);
Complex t2 = c1 - c2;
print(t2);
t2--;
print(t2);
t1++;
print(t1);
if(t1>t2)
cout << "t1 > t2"<<endl;
else if(t1==t2)
cout <<"t1==t2"<<endl;
else
cout <<"t1<t2"<<endl;
return 0;
}
#include <iostream>
using namespace std;
class Complex {
public :
Complex (double x=0,double y=0):real(x),imag(y) {}
friend Complex operator * (Complex &c1,Complex &c2);
friend Complex operator / (Complex &c1,Complex &c2);
Complex operator + (Complex &c2 );
Complex operator - (Complex &c2 );
void display();
private :
double real;
double imag;
};
Complex operator * (Complex &c1,Complex &c2) {
return Complex (c1.real*c2.real-c1.imag*c2.imag,c1.real*c2.imag+c1.imag*c2.real);
}
Complex operator / (Complex &c1,Complex &c2) {
Complex c;
c.real=(c1.real*c2.real+c1.imag*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag);
c.imag=(c1.imag*c2.real-c1.real*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag);
return c;
}
Complex Complex ::operator + (Complex &c2) {
return Complex (real+c2.real,imag+c2.imag);
}
Complex Complex ::operator - (Complex &c2) {
return Complex (real-c2.real,imag-c2.imag);
}
void Complex ::display() {
cout<<"<"<<real<<","<<imag<<"i>"<<endl;
}
int main() {
Complex c1(3,4),c2(5,-10),c3;
c1.display();
c2.display();
c3=c1+c2;
c3.display();
c3=c1-c2;
c3.display();
c3=c1*c2;
c3.display();
c3=c1/c2;
c3.display();
return 0;
}