//第二十章友元类与嵌套类 2嵌套类
//C++不光可以包含对像,还可以包含类,我们把C++所包含的类叫做嵌套类
//不过,包含对像与嵌套类有着本质的不同,包含对像只是将另一个类的对像作为该类的成员,而嵌套类似则是在该类中定义了一种新的类型,这个类型只能在该类中使用#include <iostream>
using namespace std;
class rectangle
{
public://这里直接在rectangel的公有部分定义了一个类class point{public:void setX(int x){ itsx = x;}void setY(int y){ itsy = y;}int getx()const{ return itsx;}int gety()const{ return itsy;}private:int itsx; //xint itsy; //y};point GetUpLeft()const{ return upleft; }point GetLowLeft()const{ return lowerleft;}point GetUpRight()const{ return upright;}point GetLowRight()const{ return lowerright;}//构造函数,在下面定义rectangle(int top, int left, int bottom, int right);~rectangle(){}//分别取得top left right bottom的值int GetTop()const{ return Top;}int GetLeft()const{ return Left;}int GetBottom()const{ return Bottom; }int GetRight()const{ return Right;}//设置upleft lowleft upright lowright的值void SetUpLeft(){ upleft.setX(Left); upleft.setY(Top); }void SetLowLeft(){ lowerleft.setX(Left); lowerleft.setY(Bottom); }void SetUpRight(){ upright.setX(Right); upright.setY(Top); }void SetLowRight(){ lowerright.setX(Right); lowerright.setY(Bottom); }//设置 top left right bottomvoid SetTop(int a){ Top = a;}void SetLeft(int a){ Left = a;}void SetRight(int a){ Right = a;}void SetBottom(int a){ Bottom = a;}int GetArea()const{int width = Right - Left;int height = Bottom - Top;return (width*height); }private://这四个变量的类型分别是point类型的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);upright.setX(Right);upright.setY(Top);lowerright.setX(Right);lowerright.setY(Bottom);lowerleft.setX(Left);lowerleft.setY(Bottom);
}class point
{
public:int GetArea(rectangle &rec){ return rec.GetArea(); }
};
int main()
{rectangle date(40,50,60,80);cout<<"左边为:"<<date.GetLeft()<<endl;cout<<"下边为:"<<date.GetBottom()<<endl;cout<<"左上的x坐标为:"<<date.GetLowLeft().getx()<<endl;cout<<"左上的y坐标为:"<<date.GetLowLeft().gety()<<endl;cout<<"矩形面积为:"<<date.GetArea()<<endl;cout<<"重新设置left和Bottom值"<<endl;date.SetLeft(0);date.SetBottom(100);date.SetLowLeft();cout<<"左边为:"<<date.GetLeft()<<endl;cout<<"下边为:"<<date.GetBottom()<<endl;cout<<"左上的x坐标为:"<<date.GetLowLeft().getx()<<endl;cout<<"左上的y坐标为:"<<date.GetLowLeft().gety()<<endl;point pt;cout<<"矩形面积为:"<<pt.GetArea(date)<<endl;return 0;
}