#include<iostream>
using namespace std;
class complex
{
public:
complex() :real(0), imag(0) {};
complex(float a,float b):real(a), imag(b) {};
complex operator+(complex&);
friend complex operator+(int i, complex&);
friend complex operator+(complex&, int i);
friend istream& operator>>(istream&, complex&);
friend ostream& operator<<(ostream&, complex&);
private:
float real;
float imag;
};
complex complex::operator+(complex& c2)
{
complex c;
c.real = real + c2.real;
c.imag = imag + c2.imag;
return c;
}
complex operator+(int i, complex&c2)
{
complex c;
c.real = c2.real + i;
c.imag = c2.imag;
return c;
}
complex operator+(complex& c2, int i)
{
complex c;
c.real = c2.real + i;
c.imag = c2.imag;
return c;
}
istream& operator>>(istream&input,complex &c)
{
float a, b;char s,d;
input >> c.real >> s >> c.imag>>d;
if (s == '-')c.imag -= 2 * c.imag;
return input;
}
ostream& operator<<(ostream& output, complex& c)
{
output << c.real << "+" << c.imag << "i";
return output;
}
int main()
{
complex c1, c2;int n;
complex c3, c4, c5;
cout << "请输入第一个复数c1:";cin >>c1;
cout << "请输入第二个复数c2:";cin >> c2;
cout << "请输入一个整数n:";cin >> n;
c3 = c1 + c2;c4 = c1 + n;c5 = n + c2;cout << "c1+c2、c1+n、n+c2分别为:\n";
cout << c3 << "\t" << c4 << "\t" << c5;
}
运行结果如下: