您的位置:首页 > 编程语言 > C语言/C++

C++ 实验六

2013-12-03 11:24 190 查看

实验六

类与对象(二)

【实验目的】

1、掌握类的构造函数和析构函数的概念和使用方法;

2、掌握对象数组、对象指针的定义和使用方法;

3、掌握new和delete的使用方法;

【实验内容】

1、 设计描述平面坐标上的点CPoint类,该类满足下述要求:

•具有x,y坐标信息;

•具有带默认形参值的构造函数,参数分别用于初始化x和y坐标信息;

•具有获取x、y信息的GetX和GetY函数,具有设置x、y信息的SetX和SetY函

数;

2、 设计一个矩形类CRectangle,该类满足下述要求:

•具有矩形的左下角和右上角两个点的坐标信息,这两个点的数据类型是

CPoint;

•具有带参数的构造函数CRectangle(const CPoint &, const CPoint &),参数分

别用于设置左下角和右上角两个点的坐标信息;

•具有设置左下角和设置右上角的两个点坐标的功能SetLPoint(const CPoint

&)和SetRPoint(const CPoint &);

•具有获得周长(GetPerimeter)和获得面积(GetArea)的功能。

3、 在main函数中,完成以下工作:

•动态创建一个CRectangle类的对象a_rectagnle,其初始的左下角和右上角坐

标分别为(2,5)、(6,8);调用GetPerimeter和GetArea获得矩形周长和面积,

并将周长和面积显示在屏幕上;

•调用SetLPoint设置a_rectagnle的左下角为(4,6),调用SetRPoint设置

a_rectagnle的右上角为(7,9);调用GetPerimeter和GetArea获得矩形周长和面

积,并将周长和面积显示在屏幕上;

•销毁该动态创建的对象。

#include<iostream>
using namespace std;
class CPoint{
public:
CPoint(double xd=0,double yd=0):x(xd),y(yd){
}
double GetX(){
return x;
}
double GetY(){
return y;
}
void SetX(double xi){
x=xi;
}
void SetY(double yi){
y=yi;
}

private:
double x,y;
};
class CRectangle
{
public:
CRectangle(const CPoint &a, const CPoint &b)
{
ldPoint=a;
ruPoint=b;
}
void SetLPoint(const CPoint& l)
{
ldPoint=l;
}
void SetRPoint(const CPoint& r)
{
ruPoint=r;
}
double GetPerimeter()
{
return (ruPoint.GetX()-ldPoint.GetX()+ruPoint.GetY()-ldPoint.GetY())*2;
}
double GetArea()
{
return (ruPoint.GetX()-ldPoint.GetX())*(ruPoint.GetY()-ldPoint.GetY());
}
private:
CPoint ldPoint,ruPoint;
};
int main(){
CPoint zuo(2,5),you(6,8);
CRectangle *rect=new CRectangle(zuo,you);
cout<<rect->GetPerimeter()<<endl<<rect->GetArea()<<endl;
zuo.SetX(4);
zuo.SetY(6);
you.SetX(7);
you.SetY(9);
rect->SetLPoint(zuo);
rect->SetRPoint(you);
cout<<rect->GetPerimeter()<<endl<<rect->GetArea()<<endl;
delete rect;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: