#include<iostream>
using namespace std;
class Complex
{
private:
double real;
double imag;
public:
Complex(double r=0 , double i=0);
~Complex()
{}
void print()
{
cout << real;
if (imag != 0)
{
if (imag > 0)
cout << “+”;
cout << imag << “i”;
}
cout << endl;
}
friend Complex operator+(const Complex &a, const Complex &b); //用友元函数重载双目运算符+
friend Complex operator-(const Complex &a, const Complex &b); //用友元函数重载双目运算符-
Complex operator*(const Complex &b) //成员函数重载*
{
Complex a(*this);
Complex temp;
temp.real = a.real * b.real;
temp.imag = a.imag * b.imag;
return temp;
}
Complex operator/(const Complex &b) //成员函数重载/
{
Complex a(*this);
Complex temp;
temp.real = a.real / b.real;
temp.imag = a.imag / b.imag;
return temp;
}
friend Complex operator++(Complex &a); //友元函数重载前++
Complex operator++(int) //成员函数重载后++
{
Complex temp(*this);
real++;
imag++;
return temp;
}
};
Complex operator+(const Complex &a, const Complex &b)
{
Complex temp;
temp.real = a.real + b.real;
temp.imag = a.imag + b.imag;
return temp;
}
Complex operator-(const Complex &a, const Complex &b)
{
Complex temp;
temp.real = a.real – b.real;
temp.imag = a.imag – b.imag;
return temp;
}
Complex operator++(Complex &a)
{
++a.real;
++a.imag;
return a;
}
int main()
{
Complex A1(2.3, 4.6), A2(3.6, 2.8);
Complex A3, A4, A5, A6;
A3 = A1 + A2;
A4 = A1 – A2;
A5 = A1*A2;
A6 = A1 / A2;
cout << “A1=”;
A1.print();
cout << endl << “A2=”;
A2.print();
cout << endl << “A3=A1+A2=”;
A3.print();
cout << endl << “A4=A1-A2=”;
A4.print();
cout << endl << “A5=A1*A2=”;
A5.print();
cout << endl << “A6=A1/A2=”;
A6.print();
A3 = ++A1;
cout << endl << “after A3=++A1”;
cout << “A1=”;
A1.print();
cout << “A3=”;
A3.print();
A4 = A2++;
cout << endl << “after A4=A2++”;
cout << “A2=”;
A2.print();
cout << “A4=”;
A4.print();
return 0;
}