• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

plank george

人生豪迈,只不过是重头再来。
  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

c++中的运算符重载

运算符重载是c++的特色功能之一,利用运算符重载可以很方便的进行复数一类数据的处理,如下

 

#include<iostream>
using namespace std;
class fushu
{
 double shibu,xubu;
public:
 fushu(double a=0,double b=0)
 {
  shibu=a;
  xubu=b;
 }
 fushu operator +(fushu &c);
 fushu operator -(fushu &c);
 void operator =(fushu &c);//作为单目运算符只需要一个参数
 void operator +=(fushu &c);
 void operator -=(fushu &c);
 fushu operator *(fushu &c);
 fushu operator /(fushu &c);
 void output()
 {
  cout<<"实部是"<<shibu<<"  虚部是 "<<xubu<<endl;
 }
};
void fushu::operator =(fushu &c)//类型,类名,重载的运算符的,形参表
{
// fushu temp;
 xubu=c.xubu;//经过试验验证的单目运算重载方式 ,让人颇有成就感啊
 shibu=c.shibu;
 //return temp;
}
fushu fushu::operator +(fushu &c)
{
 fushu temp;
 temp.xubu=xubu+c.xubu;
 temp.shibu=shibu+c.shibu;
 return temp;
}
fushu fushu::operator -(fushu &c)
{
 fushu temp;
 temp.xubu=xubu-c.xubu;
 temp.shibu=shibu-c.shibu;
 return temp;
}
fushu fushu::operator *(fushu &c)
{
 fushu temp;
 temp.xubu=shibu*c.xubu+xubu*c.shibu;
 temp.shibu=shibu*c.shibu-xubu*c.xubu;
 return temp;
}
fushu fushu::operator /(fushu &c)
{
 fushu temp;
 temp.xubu=(xubu*c.shibu-shibu*c.xubu)/(c.shibu*c.shibu+c.xubu*c.xubu);
 temp.shibu=(shibu*c.shibu+xubu*c.xubu)/(c.shibu*c.shibu+c.xubu*c.xubu);
 return temp;
}
void fushu::operator +=(fushu &c)
{
 xubu+=c.xubu;
 shibu+=c.shibu;
}
void fushu::operator -=(fushu &c)
{
 xubu-=c.xubu;
 shibu-=c.shibu;
}
int main()
{
 fushu c1(1,2),c2(2,3),c3;
 c3=c1;
 cout<<"c3=";
 c3.output();
 cout<<"c1-c2的结果";
 c3=c1-c2;
 c3.output();
 cout<<"c1+c2的结果";
 c3=c1+c2;
 c3.output();
 c3=c1*c2;
 cout<<"c1*c2的结果";
 c3.output();
 c3=c1/c2;
 cout<<"c1/c2的结果";
 c3.output();
 c3=c1;
 c3+=c2;
 cout<<"c1+=c2的结果";
 c3.output();
 c3=c1;
 c3-=c2;
 cout<<"c1-=c2的结果";
 c3.output();
 return 0;
}

 

单目运算符比双目运算复少一个参数,这里要是把重载后的运算符看成函数的话就会好理解很多。~。。~

posted on 2013-03-28 00:48  plank george  阅读(194)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3