#include<iostream>
#include<string>
using namespace std;
class Complex {
private:
int real;
int imag;
public:
Complex(int r, int i) {
real = r;
imag = i;
}
void show() {
cout << "real=" << real << " imag=" << imag << endl;
}
Complex operator++()//前缀++
{
++real;
++imag;
return *this;
}
Complex operator++(int);//后缀++
friend Complex operator+(Complex&, Complex&);//复数相加
friend Complex operator-(Complex&, Complex&);//复数相减
friend Complex operator+(Complex& A, int C)//复数+整数(复数在前)
{
Complex temp(A);
temp.real += C;
return temp;
}
friend Complex operator+(int, Complex&);//整数+复数(整数在前)
friend Complex operator-(Complex&, int);//复数-整数(复数在前)
friend Complex operator-(int C, Complex& A) //整数-复数(整数在前)
{
Complex temp(A);
temp.real -= C;
return temp;
}
Complex operator--() //前缀--
{
--real;
--imag;
return *this;
}
Complex operator--(int);//后缀--
friend Complex operator*(Complex& A, Complex& B)//复数相乘
{
Complex temp(A);
temp.real = A.real * B.real - A.imag * B.imag;
temp.imag = A.real * B.imag + A.imag * B.real;
return temp;
}
friend Complex operator/(Complex& A, Complex& B)//复数相除
{
Complex temp(A);
temp.real = (A.real * B.real - A.imag * B.imag) / (B.imag * B.imag + B.real * B.real);
temp.imag = (A.real * B.imag + A.imag * B.real ) / (B.imag * B.imag + B.real * B.real);
return temp;
}
};
Complex Complex::operator++(int) {
Complex temp(*this);
real++;
imag++;
return temp;
}
Complex operator+(Complex& A, Complex& B) {
Complex temp(A);
temp.real += B.real;
temp.imag += B.imag;
return temp;
}
Complex operator-(Complex& A, Complex& B) {
Complex temp(A);
temp.real -= B.real;
temp.imag -= B.imag;
return temp;
}
Complex operator+(int C, Complex& A) {
Complex temp(A);
temp.real += C;
return temp;
}
Complex operator-(Complex& A, int C) {
Complex temp(A);
temp.real -= C;
return temp;
}
Complex Complex::operator--(int) {
Complex temp(*this);
real--;
imag--;
return temp;
}
int main() {
Complex c1(1, 2), c2(3, 4), c3(5, 6), c4(7, 8), c5(9, 1),c6(0,0);
Complex& c7=c1;
c6 = c1 +c2;
c6.show();
c6 = c1 - c2;
c6.show();
c6 = c5++;
c6.show();
c5.show();
c6 = c4--;
c6.show();
c4.show();
c6 = c2 * c1;
c6.show();
c6 = c2 / c1;
c6.show();
}
运行结果:
real=4 imag=6
real=-2 imag=-2
real=9 imag=1
real=10 imag=2
real=7 imag=8
real=6 imag=7
real=-5 imag=10
real=-1 imag=2