矩形类简单实现(c++)

#include<iostream>
#include<string>
using namespace std;


class Rectangle //基类
{
public:
Rectangle(int x=0,int y=0,int h=0,int w=0)
:xLow(x),yLow(y),height(h),width(w)
{
}
~Rectangle()
{
}
int Getheight()const
{
return height;
}
int Getwidth() const
{
return width;
}
int Getxpos() const
{
return xLow;
}
int Getypos() const
{
return yLow;
}
void Setpos(int x,int y)
{
xLow=x;
yLow=y;
}
void Setheight(int h)
{
height=h;
}
void Setwidth(int w)
{
width=w;
}
bool operator==(const Rectangle& s);
private:
int xLow,yLow,height,width;
};


bool Rectangle::operator ==(const Rectangle& s)
{
if(this==&s) return true;
if((Getxpos()==s.Getxpos()) && (Getwidth()==s.Getwidth()) &&(Getheight()==s.Getheight()) &&(Getypos()==s.Getypos())) return true;
else return false;
}


ostream& operator<<(ostream& os,Rectangle& r)
{
os<<"Position is: "<<r.Getxpos()<<" ";
os<<r.Getypos()<<endl;
os<<"Height is: "<<r.Getheight()<<endl;
os<<"Width is: "<<r.Getwidth()<<endl;
return os;
}
bool operator<(const Rectangle& r1,const Rectangle& r2)
{
if(r1.Getheight()*r1.Getwidth()<r2.Getheight()*r2.Getwidth()) return true;
else return false;
}
//--------------------------------------------------------------------------------------------------------------------------------------------------
class MyRectangle:public Rectangle //派生类
{
public:
MyRectangle(int x=0,int y=0 ,int h=0, int w=0,string c="black")
:Rectangle(x,y,h,w),color(c)
{
}

~MyRectangle()
{
}
string Getcolor()const
{
return color;
}
int area()
{
return Getheight()*Getwidth();
}
int petimeter()
{
return (Getheight()+Getwidth())*2;
}
void Setcolor(string c)
{
color=c;
}


private:
string color;
};


ostream& operator<<(ostream& os,MyRectangle& r)//重载输出操作符
{
os<<"Position is: "<<r.Getxpos()<<" ";
os<<r.Getypos()<<endl;
os<<"Height is: "<<r.Getheight()<<endl;
os<<"Width is: "<<r.Getwidth()<<endl;
os<<"Color is: "<<r.Getcolor()<<endl;
return os;
}
istream& operator>>(istream& is,MyRectangle& r)//重载输入操作符
{
int x,y,h,w;
string c;
char ch1,ch2,ch3,ch4,ch5,ch6;
is>>ch1>>x>>ch2>>y>>ch3>>h>>ch4>>w>>ch5>>c>>ch6; //输入时别忘了各个变量之间加空格
if(!is) return is;
if(ch1!='('||ch2!=','||ch3!=','||ch4!=','||ch5!=','||ch6!=')')
{
is.clear (ios_base::failbit);
return is;
}
r.Setcolor (c);
r.Setheight(h);
r.Setwidth(w);
r.Setpos(x,y);
return is;
}
int main()
{
MyRectangle r(3,3,4,5,"blue");
cout<<r;
MyRectangle r1;
cin>>r1;
cout<<r1.area()<<endl;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值