有趣的运算符重载知识点

#include <iostream.h>
//using namespace std;

class complex{
protected:
 int real,imag;
public:
 complex(int a=0, int b=0)
 {
  real = a;
  imag = b;
 }
 void display()
 {
  cout<<real<<"+"<<imag<<"i"<<endl;
 }
 friend complex operator+(complex& a, complex& b);
 friend complex operator-(complex& a, complex& b);
 friend complex operator*(complex& a, complex& b);
 friend complex operator/(complex& a, complex& b);
 friend complex operator++(complex &);
 friend complex operator++(complex &,int);
 complex operator=(complex &a);  //=不能用友元重载
};

complex operator+(complex& a, complex& b)
{
 complex c;
 c.real = a.real + b.real;
 c.imag = a.imag + b.imag;
 return c;
}

complex operator -(complex& a, complex& b)
{
 complex c;
 c.real = a.real - b.real;
 c.imag = a.imag - b.imag;
 return c;
}

complex operator *(complex& a, complex& b)
{
 complex c;
 c.real = a.real * b.real - a.imag * b.imag;
 c.imag = a.real * b.imag + a.imag * b.real;
 return c;
}

complex operator /(complex& a, complex& b)
{
 complex c;
 c.real = (a.real * b.real + a.imag * b.imag) / (a.imag * a.imag +
b.imag * b.imag);
 c.imag = (a.imag * b.real - a.real * b.imag) / (a.imag * a.imag +
b.imag * b.imag);
 return c;
}
complex operator++(complex & a,int) //++n,编译器自动识别的,对于第二个参数是int,就是++n
{
 complex c;
 c.real = ++a.real;
 c.imag = ++a.imag;
 return c;

}

complex operator++(complex & a)//n++,编译器自动识别的,对于第二个参数没有,就是n++,跟里面的具体实现无关。若这个函数没写,则不管是n++,还是++n,都用上面那个++函数实现,但是会出现警告。
{
 complex c;
 c.real = a.real;
 c.imag = a.imag;
 a.real++;
 a.imag++;
 return c;
}

complex complex::operator=(complex &a)
{
 real = a.real;
 imag = a.imag;
 return *this;
}


void main()
{
 complex one(3,4), two(1,2), three;
 three = one + two;
 three.display();

 three = one - two;
 three.display();

 three = one * two;
 three.display();

 three = one / two;
 three.display();

 one++;
 one.display();

 one++;
 one.display();

 three = one;
 three.display();

 
 
 complex four;
 four = one++;   
 four.display();
 one.display();
 ++one;
 one.display();
 four = ++one;
 four.display();
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值