# 运算符重载——重载+和-对复数类对象进行加减运算

1.题目：

### Sample Input

100 20 -10 18
2 2 2 4


### Sample Output

90+38i 110+2i
4+6i -2i

2.想法：

这道题目主要是要考虑输出时的集中特殊情况，有实部和虚部都为0，还有虚部为1，-1，整数，负数的情况。静下心来其实不难的。

3.参考代码一：

#include <iostream>
using namespace std;

class Complex
{
private:
double real, image;
public:
Complex(double r = 0, double i = 0);
Complex operator+(Complex&);
Complex operator-(Complex&);
void show();
};

Complex::Complex(double r, double i)
{
real = r;
image = i;
}

Complex Complex::operator+(Complex& c)
{
Complex x;
x.real = real + c.real;
x.image = image + c.image;
return x;
}

Complex Complex::operator-(Complex& c)
{
Complex x;
x.real = real - c.real;
x.image = image - c.image;
return x;
}

void Complex::show()
{
if (real == 0) {
if (image == 0)
cout << 0;
else if (image == 1)
cout << "i";
else if (image == -1)
cout << "-i";
else if (image > 0)
cout << image << "i";
else if (image < 0)
cout << image << "i";
} else {
if (image == 0)
cout << real;
else if (image == 1)
cout << real << "+i";
else if (image == -1)
cout << real << "-i";
else if (image > 0)
cout << real << "+" << image << "i";
else if (image < 0)
cout << real << image << "i";
}
}

int main()
{
double a, b, c, d;

while (cin >> a >> b >> c >> d) {
Complex x(a, b), y(c, d), z, w;
z = x + y;
z.show();
cout << " ";
w = x - y;
w.show();
cout << endl;
}

return 0;
}



#include <iostream>
using namespace std;

class Complex
{

private:
double real, image;

public:
Complex(double r = 0, double i = 0);
Complex& operator+(Complex&);
Complex& operator-(Complex&);
void show();

};

Complex::Complex(double r, double i)
{
real = r;
image = i;
}

Complex& Complex::operator+(Complex& c)
{
Complex x;
x.real = real + c.real;
x.image = image + c.image;
return x;
}

Complex& Complex::operator-(Complex& c)
{
Complex x;
x.real = real - c.real;
x.image = image - c.image;
return x;
}

void Complex::show()
{
if (image == 0) {
if (real == 0)
cout << "0";
else
cout << real;
} else if (image == 1) {
if (real == 0)
cout << "i";
else
cout << real << "+i";
} else if (image == -1) {
if (real == 0)
cout << "-i";
else
cout << real << "-i";
} else {
if (real == 0)
cout << image << "i";
else {
if (image > 0)
cout << real << "+" << image << "i";
else
cout << real << image << "i";
}
}
}

int main()
{
double a, b, c, d;

while (cin >> a >> b >> c >> d) {
Complex x(a, b), y(c, d), z, w;

z = x + y;
z.show();
cout << " ";

w = x - y;
w.show();
cout << endl;
}

return 0;
}