C++ Complex类运算符重载
2013-05-07 21:18 wuzhang 阅读(2085) 评论(0) 编辑 收藏 举报所谓重载,就是重新赋予新的含义。
函数重载就是对一个已有的函数赋予新的含义,使之实现新功能。运算符也可以重载。实际上,我们已经在不知不觉之中使用了运算符重载。
现在要讨论的问题是: 用户能否根据自己的需要对C++已提供的运算符进行重载,赋予它们新的含义,使之一名多用。譬如,能否用“+”号进行两个复数的相加。在C++中不能在程序中直接用运算符“+”对复数进行相加运算。用户必须自己设法实现复数相加。
例如:1. 编写一个简单复数类SComplex,要求用友元函数重载"+"、"-"、"*"、"/"、 "<<"、">>"运算符,
用成员函数重载"="运算符,使之能够实现整数或浮点数和复数的四则运算和标准流的输入输出,并且进行测试。
#include<iostream>
#include<iomanip>
using namespace std;
class SComplex
{
public:
double img,real;
public:
//SComplex(){} //无参构造函数
SComplex(double x=0,double y=0) //有参构造函数
{
real=x;
img=y;
}
void print();
friend SComplex operator+(const SComplex&c1,SComplex&c2);
friend SComplex operator-( SComplex&c1,SComplex&c2);
friend SComplex operator*( SComplex&c1,SComplex&c2);
friend SComplex operator/( SComplex&c1,SComplex&c2);
SComplex& operator=(const SComplex &);
friend ostream& operator << (ostream&,SComplex&); //运算符“<<”重载为友元函数
friend istream& operator >> (istream&,SComplex&); //运算符“>>”重载为友元函数
SComplex add(SComplex &c1,SComplex &c2); //自定义加法运算
SComplex operator++(); //自加运算
};
void SComplex::print()
{
cout<<showpos<<real<<showpos<<img<<"i"<<"\n"<<endl;
}
SComplex operator+(const SComplex &c1,SComplex &c2)
{
SComplex temp(c1.real+c2.real,c1.img+c2.img);
return temp;
}
SComplex operator-( SComplex &c1,SComplex &c2)
{
SComplex temp;
temp.real=c1.real-c2.real;
temp.img=c1.img-c2.img;
return temp;
}
SComplex::SComplex add(SComplex &c1,SComplex &c2)
{
SComplex temp;
temp.real=c1.real+c2.real;
temp.img=c1.img+c2.img;
return temp;
}
SComplex:: SComplex operator*(SComplex &c1,SComplex &c2)
{
SComplex temp;
temp.real=c1.real*c2.real-c1.img*c2.img;
temp.img=c1.real*c2.img+c1.img*c2.real;
return temp;
}
SComplex::SComplex operator/(SComplex &c1,SComplex &c2)
{
SComplex temp;
temp.real=c1.real/c2.real;
temp.img =c1.img/c2.real;
return temp;
}
SComplex& SComplex::operator=(const SComplex &c)
{
this->real=c.real;
this->img=c.img;
return *this;
}
SComplex SComplex:: operator++()
{
real++;
img++;
return *this;
}
ostream& operator << (ostream& output,SComplex& c) //定义运算符“<<”重载函数
{
if(c.real==0)
{
output<<c.img<<"i"<<endl;
}
if(c.img==0)
{
output<<c.real<<endl;
}
else if(c.real!=0&&c.img!=0)
{
output<<c.real<<c.img<<"i"<<endl;
}
return output;
}
istream& operator >> (istream& input,SComplex& c) //定义重载运算符“>>”
{
cout<<"input real and img number:"<<endl;
input>>c.real>>c.img;
return input;
}
int main()
{
SComplex c1(2,8),c2(4,-2),c3;
cout<<"复数: c1="<<setw(2);
c1.print();
cout<<"复数: c2="<<setw(2);
c2.print();
cout<<setw(6);
cout<<"重载加法:c1+c2=";
c3=c1+c2;
c3.print();
cout<<"重载输出 ";
cout<<"c1+c2=";
cout<<c3;
cout<<endl;
cout<<"重载减法: c1-c2=";
c3=c1-c2;
c3.print();
cout<<"调用加法函数:";
c3=add(c1,c2);
cout<<"c1+c2=";
c3.print();
cout<<"重载乘法: c1*c2=";
c3=c1*c2;
c3.print();
cout<<"重载除法: c1/c2=";
c3=c1/c2;
c3.print();
cout<<"重载等号: c3=";
c3=c1;
c3.print();
cout<<"重载自加: c1++=";
c3=++c2;
c3.print();
cout<<"重载输出: ";
cout<<c3;
cout<<"重载输入:"<<endl;
cin>>c1;
cout<<c1;
system("pause");
return 0;
}