面向对象程序设计 lab15 学号 班级 姓名
实验15 运算符重载,异常处理和文件操作
【实验目的】
(1)掌握运算符重载的基本方法。
(2)掌握异常和异常处理。 (3)掌握文件操作的基本方法。
【实验内容】
第一部分:教程练习
1、【编写程序】:实现以下功能
1.输入N本图书的信息:书号(6个字符)、书名(12个字符)、作者(8个字符)、单价(2位小数);将所有数据写入文件ST1.DAT中; 2.从ST1.DAT文件中读取图书数据,将价钱高于30元的图书信息输出; 3.输入书号,在ST1.DAT文件中查找该图书,找到以后输出该图书的所有数据,如果文件中没有输入的书号,给相应的提示信息。
===================源程序=======================
#include
#include
public: int id;
char name[10]; char author[10]; int price; public:
void getdata() {
cout<<\请分别输入书号,书名,作者,价格:\ cin>>id>>name>>author>>price; }
void dispdata() {
面向对象程序设计 lab15 学号 班级 姓名
cout<
void inputdata() {
ofstream outfile(\ book book1; int num;
cout<
for(int i=0;i cout<<\输入第\本书的数据:\ book1.getdata(); outfile.write((char*)&book1,sizeof(book1)); } outfile.close(); } void display() { ifstream infile(\ book book1; cout< cout< infile.read((char*)&book1,sizeof(book1)); while(infile) { if(book1.price>30) book1.dispdata(); infile.read((char*)&book1,sizeof(book1)); } infile.close(); 面向对象程序设计 lab15 学号 班级 姓名 } void main() { int a; do { cout<<\输入数据??2输入数据??others退出\ cin>>a; switch(a) { case 1: inputdata(); break; case 2: display(); break; } }while(a==1||a==2); } 第二部分:自测题 1、 多态练习: 1) 设计一个立体图形类(CStereoShape类),并满足如下要求: ?CStereoShape类有一个纯虚函数GetArea,能够获取立方体的表面积; ?CStereoShape类有一个纯虚函数GetVolume,能够获取立方体的体积 面向对象程序设计 lab15 学号 班级 姓名 2) 设计一个立方体类(CCube类),该类继承于CStereoShape类,并满足如下要求: ?CCube类有一个带参数的构造函数,其参数分别对应于立方体的长、宽、高。 ?用一个成员函数来实现对立方体长、宽、高的设置。 ?重载CStereoShape类的GetArea和GetVolume,分别完成立方体的表面积和 体积的计算。 3) 设计一个球体类 (CSphere),该类继承于CStereoShape类,并满足如下要求: ?CSphere类有一个带参数的构造函数,其参数对应于球体的半径。 ?用一个成员函数来实现对球体半径的设置。 ?重载CStereoShape类的GetArea和GetVolume,分别完成球体的表面积和体 积的计算。 4) 实现一个main函数,在main函数中至少完成如下工作: ?实例化一个CCube类的对象a_cube和CSphere类的对象c_sphere; ?定义一个CStereoShape类的指针p; ?将a_cube的长、 宽和高分别设置为4、 5和6; 将p指向a_cube, 通过p将a_cube 的表面积和体积打印到屏幕上; ?将c_sphere的半径设置为7;将p指向c_sphere,通过p将c_sphere的表面积和 体积打印到屏幕上。 #include #include virtual double GetArea(){return 0;} 面向对象程序设计 lab15 学号 班级 姓名 virtual double GetVolume(){return 0;} }; class CCube : public CSreroShape { private: double length, width, height; public: CCube(double l, double w, double h) { length = l; width = w; height = h; } ~CCube(); virtual double GetArea() const { return 2 * (length * width + length * height + height * width); } virtual double GetVolume() const { return length * width * height; } }; class CSphere : public CSreroShape { int radius; public: CSphere(int r) { radius = r; } virtual double GetArea() { return 4 * Pi * pow(radius, 2); } virtual double GetVolume() { return 4.0 / 3 * Pi * pow(radius, 3); } }; int main(void) { CCube *a_cube = new CCube(4, 5, 6); CSphere *c_sphere = new CSphere(7); CSreroShape *p; p = a_cube; cout<<\ cout<<\olume is \ delete p; p = c_sphere; cout<<\ cout<<\olume is \ delete p; return 0; } 2、设计字符串类String,用来存放不定长的字符串,重载运算符“= =”,“>”,“<”,用于两个字符串的大于、小于和等于的比较运算。 [实验提示]