#include <iostream>
using namespace std;
/*---------------------------------
第20章友元素 2.2 嵌套类
1)点坐标类point嵌套于矩形类rectangle中,它仅仅服务于矩形类,
2) 即便外部有个与它同名的类,两个类也不会产生冲突。
---------------------------------*/
class rectangle
{
public:
class point //point是rectangle的嵌套类【********】
{
public:
void setx(int n){x=n;}
void sety(int n){y=n;}
int getx(){return x;}
int gety(){return y;}
private:
int x;
int y;
};
point Getupleft()const{return upleft;} //获取矩形各个点
point Getlowerleft()const{return lowerleft;}
point Getupright()const{return upright;}
point Getlowerright()const{return lowerright;}
rectangle(int top,int left,int bottom,int right); //初始化并构造该矩形
int GetArea()const{int width=Right-Left; int height=Bottom-Top; return width*height;}
int GetTop()const{return Top;} //获取矩形的四个坐标值
int GetLeft()const{return Left;}
int GetBottom()const{return Bottom;}
int GetRight()const{return Right;}
void SetTop(int n){Top=n;} //设置矩形的四个坐标值
void SetLeft(int n){Left=n;}
void SetBottom(int n){Bottom=n;}
void SetRight(int n){Right=n;}
void SetUpleft(){upleft.setx(Left); upleft.sety(Top);} 设置矩形的四个点的坐标值
void Setlowerleft(){lowerleft.setx(Left); lowerleft.sety(Bottom);}
void Setupright(){upright.setx(Right); upright.sety(Top);}
void Setlowerright(){lowerright.setx(Right); lowerright.sety(Bottom);}
private:
point upleft; //矩形的左上角点位置
point lowerleft; //矩形的左下角点位置
point upright; //矩形的右上角点位置
point lowerright; //矩形的右下角点位置
int Top; //矩形上侧纵坐标
int Left; //矩形左侧横坐标
int Bottom; //矩形下侧纵坐标
int Right; //矩形右侧侧横坐标
};
rectangle::rectangle(int top,int left,int bottom,int right)
{
Top=top;
Left=left;
Bottom=bottom;
Right=right;
upleft.setx(Left);
upleft.sety(Top);
lowerleft.setx(Left);
lowerleft.sety(Bottom);
upright.setx(Right);
upright.sety(Top);
lowerright.setx(Right);
lowerright.sety(Bottom);
}
class point //rectangle类下的point类与此处同名,但仍旧不冲突
{
public:
int GetArea(rectangle& rec){ return rec.GetArea();}
};
int main()
{
rectangle date(40,50,60,80);
cout<<"Top:"<<date.GetTop()<<" Left:"<<date.GetLeft()<<" Bottom:"<<date.GetBottom()<<" Right:"<<date.GetRight()<<endl;
cout<<"矩形左侧横坐标Left为:"<<date.GetLeft()<<endl;
cout<<"矩形下侧纵坐标Bottom为:"<<date.GetBottom()<<endl;
cout<<"矩形左下角点的x坐标为:"<<date.Getlowerleft().getx()<<endl;
cout<<"矩形左下角点的y坐标为:"<<date.Getlowerleft().gety()<<endl;
cout<<"矩形的面积为:"<<date.GetArea()<<endl;
cout<<"重新设置Left和bottom值..."<<endl;
date.SetLeft(0);
date.SetBottom(100);
date.Setlowerleft();
cout<<"矩形左侧横坐标Left为:"<<date.GetLeft()<<endl;
cout<<"矩形下侧纵坐标Bottom为:"<<date.GetBottom()<<endl;
cout<<"矩形左下角点的x坐标为:"<<date.Getlowerleft().getx()<<endl;
cout<<"矩形左下角点的y坐标为:"<<date.Getlowerleft().gety()<<endl;
cout<<"矩形的面积为:"<<date.GetArea()<<endl;
point po; //2) 即便外部有个与它同名的类,两个类也不会产生冲突。【********】
cout<<"类外同名类调用=》矩形的面积为:"<<po.GetArea(date)<<endl;
return 0;
}
运行结果:
Top:40 Left:50 Bottom:60 Right:80
矩形左侧横坐标Left为:50
矩形下侧纵坐标Bottom为:60
矩形左下角点的x坐标为:50
矩形左下角点的y坐标为:60
矩形的面积为:600
重新设置Left和bottom值...
矩形左侧横坐标Left为:0
矩形下侧纵坐标Bottom为:100
矩形左下角点的x坐标为:0
矩形左下角点的y坐标为:100
矩形的面积为:4800
类外同名类调用=》矩形的面积为:4800
Press any key to continue