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 阅读(189) 评论(0) 编辑 收藏 举报