运算符重载!

实验六  运算符重载
1、实验目的
理解运算符重载(非成员形式和成员形式)、学习重载几类运算符(++,=,!=,+,-,==等)。
2、实验内容
应用VC++6.0的构建一个复数类Complex,试对下列几个运算符进行重载:++,=,!=,+,-,==,其中要求要有成员重载形式和友元重载形式,而且,++运算符要求实现先加和后加两种形式。


# include<iostream.h>
class complex{
public:
    double real;
double imag;
complex(double x,double y) //构造函数;
{
  real=x;
  imag=y;
}
friend complex operator -(complex a,complex b);   //用友元函数对-号重载;
friend int operator==(complex a,complex b);
friend int operator!=(complex a,complex b);
    complex operator++();                        //用成员函数对前加++重载;
complex operator++(int);                         //用成员函数对后加++重载;
complex operator=(complex a)                     //用成员函数对=重载;
{
  real=a.real;
  imag=a.imag;
  return *this;
}
void show()      //成员函数用于输出;
{
  cout<<"real :"<<real<<endl;
  cout<<"imag :"<<imag<<endl;
}


};
complex operator+(complex a,complex b)   //++的友元重载函数进行定义;
{
complex temp(0.0,0.0);
temp.real=a.real+b.real;
temp.imag=a.imag+b.imag;
return temp;
}
complex operator-(complex a,complex b)
{
complex temp(0.0,0.0);
temp.real=a.real-b.real;
    temp.imag=a.imag-b.imag;
return temp;
}
int operator==(complex a, complex b)
{
  if(a.real==b.real&&a.imag==b.imag)
   return 1;
  return 0;
}
int operator!=(complex a ,complex b)
{
if(a.imag!=b.imag||a.real!=b.real)
  return 1;
return 0;
}
complex complex::operator ++()    //对符号++成员重载函数进行类外定义;
{
real=real+real;
imag=imag+imag;
return *this;      //返回当前对象;
}
complex complex::operator ++(int)
{
++real;
++imag;
return *this;   //返回当前对象;
}


void main()    //主函数;
{
complex com1(1.1,2.2),com2(3.3,4.4),total(1.1,2.2),ca(0.0,0.0),fuzhi(0.0,0.0);
if(com1==total)
  cout<<"you yuan xiang deng"<<endl;
if(com1!=com2)
  cout<<"you  yuan  bu xiang deng "<<endl;
total=com1+com2;
ca=com2-com1;
cout<<"lei wai jia hao : "<<endl;
total.show();
cout<<"you yuan jian hao : "<<endl;
ca.show();
fuzhi=com1;
cout<<"fu zhi real:"<<endl;
fuzhi.show();                //调用成员函数
com1++;
++com2;
cout<<"qian  zhui"<<endl;
com1.show();                //调用成员函数
cout<<"hou  zhui :"<<endl;
com2.show();                //调用成员函数;
return ;

}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值