书上有一个用C++设计自己的输出/输入操作,涉及到运算符重载和流提取符重载,挺不错的!
代码如下:
COMPLEX.HPP文件
#include<iostream.h>
class COMPLEX {
public :
COMPLEX(double r=0,double i=0);
COMPLEX(const COMPLEX& other);
COMPLEX operator +(const COMPLEX& other);
COMPLEX operator -(const COMPLEX& other);
COMPLEX operator -();
COMPLEX operator =(const COMPLEX &other);
friend ostream& operator <<(ostream& stream,COMPLEX& obj);
friend istream& operator <<(istream& stream,COMPLEX& obj);
public :
double real,image;
};
COMPLEX.CPP文件
//COMPLEX.CPP文件
#include "COMPLEX.HPP" //将头文件包括进去,不能写成include<COMPLEX.CPP>。。。
COMPLEX::COMPLEX(double r,double i)
{
real=r;
image=i;
return ;
}
COMPLEX::COMPLEX(const COMPLEX& other)
{
real=other.real;
image=other.image;
return ;
}
COMPLEX COMPLEX::operator +(const COMPLEX& other) //运算符+重载 参数为COMPLEX类型,返回值为COMPLEX类型的引用,下同
{
COMPLEX temp;
temp.real=real+other.real;
temp.image=image+other.image;
return temp;
}
COMPLEX COMPLEX::operator -(const COMPLEX& other)
{
COMPLEX temp;
temp.real=real-other.real;
temp.image=image-other.image;
return temp;
}
COMPLEX COMPLEX::operator =(const COMPLEX& other)
{
real=other.real;
image=other.image;
return *this;
}
ostream& operator<<(ostream& stream,COMPLEX& obj) //流提取符重载有两个参数,第一个参数出现在<<操作符左侧,为ostream引用,第二个出现在操作符<<右侧,为COMPLEX引用,返回值是一个ostream的对象引用,下同
{
stream<<obj.real;
if(obj.image>0) stream<<"+"<<obj.image<<"i";
else if(obj.image<0) stream<<obj.image<<"i";
return stream;
}
istream& operator>>(istream& stream,COMPLEX& obj)
{
cout<<"Input real part:";
stream>>obj.real;
cout<<"input image part:";
stream>>obj.image;
return stream;
}
int main()
{
COMPLEX c1,c2;
cout<<"Input the first complex number c1:"<<endl;
cin>>c1;
cout<<"Input the second compex number c2:"<<endl;
cin>>c2;
cout<<"c1 is"<<c1<<endl;
cout<<"c2 is"<<c2<<endl;
cout<<"c1+c2 is "<<c2+c1<<endl;
cout<<"c1-c2 is "<<c1-c2<<endl;
//操作符原功能任存在
int a=50,b=10;
cout<<"A="<<a<<"\tB"<<b<<endl;
cout<<"A+B is "<<a+b<<endl;
cout<<"A-B is "<<a-b<<endl;
a=-b;
cout<<"A=-B,A="<<a<<"\tB"<<b<<endl;
a=b;
cout<<"A=B,A="<<a<<"\tB"<<b<<endl;
return 0;
}
输出结果:
posted on 2010-09-02 22:08
jince 阅读(496)
评论(0) 编辑 收藏 引用 所属分类:
C++学习