#include
using std::cout;
using std::endl;
//using namespace std;
class complex
{
private:
double real;
double image;
public:
complex(double real=0.0,double image = 0.0)
{
this->real=real,this->image=image;
}
void display()
{
cout<<"("<
friend complex operator + (complex A,complex B)
{
return complex(A.real + B.real, A.image + B.image);
}
friend complex operator - (complex A, complex B);
friend complex operator - (complex A);
friend complex operator ++ (complex &A);
friend complex operator ++ (complex &A, int);
};
complex operator - (complex A, complex B)
{
return complex(A.real-B.real , A.image - B.image);
}
complex operator - (complex A)
{
return complex(-A.real, -A.image);
}
complex operator ++ (complex &A)
{
return complex(++A.real, A.image);
}
complex operator ++ (complex &A, int)
{
return complex(A.real++, A.image);
}
int main()
{
complex A(100.0,200.0), B(-10.0,20.0),C;
cout<<"A=", A.display();
cout<<"B=", B.display();
C=A+B;
cout<<"C=A+B", C.display();
C=A-B;
cout<<"C=A-B", C.display();
C=-A+B;
cout<<"C=-A+B", C.display();
C=A++;
cout<<"C=A++", C.display();
C=++A;
cout<<"C=++A", C.display();
C=A+5;
C.display();
return 0;
}
你好 具体实现如下:
#include
using namespace std;
class complex
{
public:
complex(){} ;
complex(double r, double i)
{
real = r, imag = i;
}
complex operator +(const complex &c);
complex operator -(const complex &c);
friend void print(const complex &c);
private:
double real, imag;
};
inline complex complex::operator +(const complex &c)
{
return complex(real + c.real, imag + c.imag);
}
inline complex complex::operator -(const complex &c)
{
return complex(real - c.real, imag - c.imag);
}
void print(const complex &c)
{
if(c.imag<0)
cout<
cout<
void main()
{
complex c1(2.0, 3.0), c2(4.0, -2.0), c3;
c3 = c1 + c2;
cout<<"\nc1+c2=";
print(c3);
c3 = c1 - c2;
cout<<"\nc1-c2=";
print(c3);
cout<
希望能帮助你哈