复数类重载主要实现二元操作符(参数中有一个该类的对象)‘+’、‘-’和一元操作符(参数中没有该类的对象)、‘-a’(取负)。

代码:

#include <iostream>
using namespace std ;
class complex
{
 public:
 complex() {
 
 }
 complex(int r, int i) {real=r; p_w_picpath=i;}
 complex(const complex&) ;
 complex operator +(const complex&);
 complex operator -(const complex&);
 complex operator -();
 void print();
 private:
 int real, p_w_picpath;
};

complex::complex(const complex &c)
{
 real = c.real;
 p_w_picpath = c.p_w_picpath;
}

complex complex::operator +(const complex &c )
{
 real += c.real;
 p_w_picpath += c.p_w_picpath;
 return *this;
}

complex complex::operator -(const complex &c )
{
 complex temp;
 temp.real = real - c.real;
 temp.p_w_picpath= p_w_picpath - c.p_w_picpath ;
 return temp;
}

complex complex::operator-()
{
 real *= -1;
 p_w_picpath *=-1;
 return *this;
}

void complex::print()
{
 cout << real;
 if(p_w_picpath>0) cout << "+" << p_w_picpath << "i" << endl;
 else if(p_w_picpath<0) cout << p_w_picpath << "i" << endl ;
 else cout << endl ;
}
int main()
{
 complex obj(1,2), obj1(1,-2);
 obj.print() ;
 obj1.print() ;
 obj = obj + obj1 ;
 obj.print() ;
 obj = obj-obj1 ;
 obj.print() ;
 (-obj).print();
 return 0 ;
}