<pre name="code" class="cpp">/***************************************/
重载运算符的学习2015年8月
/**************************************/
#include <iostream>
using namespace std;
class ApRect{
public:
//
ApRect(){}
ApRect(double ht,double wid){height=ht;width=wid;}
//
double Area(){return height*width;}
double Width(){return width;}
double Height(){return height;}
//
friend istream& operator >>(istream& in,ApRect& cls);
//
friend ostream& operator <<(ostream& out,ApRect& cls);
//
double operator + (const ApRect rect);
//
double operator [] (const int index);
//
friend bool operator > (ApRect rect_1, ApRect rect_2_);
bool operator < (ApRect rect);
//
~ApRect(){}
private:
double height;
double width;
};
istream& operator >> (istream& in, ApRect& cls){
cout<<"input height and width:";
in>>cls.height>>cls.width;
return in;
}
ostream& operator <<(ostream& out, ApRect& cls){
out<<"height:"<<cls.height<<";width:"<<cls.width;
return out;
}
double ApRect::operator +(ApRect rect){
return Area()-rect.Area();
}
double ApRect::operator [](int a){
switch(a){
case 0:
return Height();break;
case 1:
return Width();break;
case 2:
return Area();break;
default:
return 0.0;break;
}
}
bool operator >(ApRect rect_1,ApRect rect_2){
return (rect_1.Area()>rect_2.Area()) ? true:false;
}
bool ApRect::operator <(ApRect rect){
return (Area()<rect.Area()) ? true:false;
}
int main(){
ApRect rect_1;
ApRect rect_2(10,20);
cin>>rect_1;
cout<<endl<<"rect_1"<<rect_1<<endl;
cout<<"rect_2:"<<rect_2<<endl<<endl;
//add
cout<<"+:"<<rect_1+rect_2<<endl;
return 0;
}