习题及实验讲解(10-11章).doc
文本预览下载声明
/* 习题10.13:定义一个矩形类Rect,矩形的左上角坐标(Left,Top)和右下角坐标(Right,Bottom)定义为私有数据成员,成员函数包括计算面积、计算周长、输入和输出。定义Rect类数组,计算各个矩形的面积和周长并输出。*/
/*#includeiostream
using namespace std;
class Rect{
private:
float left, top;
float right, bottom;
float length, area; //此两成员可不用
public:
void input(float le, float to, float ri, float bo) //输入函数,输入数据成员 { left=le; top=to; right=ri; bottom=bo; }
void input( ) //重载输入函数,用于数组输入
{ coutInput left, top and right, bottom:;
cinlefttoprightbottom; } //无参,直接输入数据成员的值
float getLength( ) //无参,有返回值(也可无返回值)
{ length=((top-bottom)+(right-left))*2;
return length;
}
void getArea( ) //无返回值
{ area=(top-bottom)*(right-left); }
void Output(); //体内声明函数
};
void Rect::Output( ) //体外定义函数
{ cout(left,top)=(left,top)endl;
cout(right,bottom)=(right,bottom)endl;
coutLength=getLength(),Area=areaendl; //用返回值
}
int main(void)
{ Rect rect1; //定义Rect类的对象rect1
rect1.input(2,4,4,2); //rect1的数据成员的值作为实参输入
rect1.getLength(); //数据的输入、计算和输出均通过对象的函数成员进行
rect1.getArea();
rect1.Output();
Rect r[2]; //定义Rect类的对象数组
int i;
for(i=0; i2; i++)
{ r[i].input(); //键盘输入数组元素,此时用前一种实参的输入方式就不方便
r[i].getLength();
r[i].getArea();
r[i].Output();
}
return 0;
}
此题中对象数组数据的输入未采用构造函数的形式,而是采用专门的输入??数。
/* 习题10.17 设计一大小可变的整形数组类:
class CArray{
int size; //数组的元素个数
int *p; //指向为数组申请的动态内存
public:
CArray(int=100); //数组缺省大小为100个元素
~CArray(); //析构函数
int GetElem(int i); //取或设置数组中的第i个元素
void Input(); //为数组所有元素输入数据
void Print(); //输出数组中的所有元素
void Sort() //对数组元素进行排序
int Search(int); //在数组中查找指定值
};
首先完成CArray类中成员函数的定义,然后设计主函数,定义CArray的对象,测试所定义的类CArray。*/
/*#includeiostream
using namespace std;
class CArray
显示全部