書上有一個(gè)用C++設(shè)計(jì)自己的輸出/輸入操作,涉及到運(yùn)算符重載和流提取符重載,挺不錯(cuò)的!
代碼如下:
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" //將頭文件包括進(jìn)去,不能寫成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) //運(yùn)算符+重載 參數(shù)為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) //流提取符重載有兩個(gè)參數(shù),第一個(gè)參數(shù)出現(xiàn)在<<操作符左側(cè),為ostream引用,第二個(gè)出現(xiàn)在操作符<<右側(cè),為COMPLEX引用,返回值是一個(gè)ostream的對(duì)象引用,下同


{
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;
}
輸出結(jié)果:
posted on 2010-09-02 22:08
jince 閱讀(500)
評(píng)論(0) 編輯 收藏 引用 所屬分類:
C++學(xué)習(xí)