C++实验12 对象的持久化和异常

实验十二 对象的持久化和异常

1 实验目的

(1)学习对象的持久化方法 —— 文件操作
(2)学习如何读取和写入文本文件
(3)学习如何读取和写入二进制固定长文件
(4)正确理解 C++的异常处理机制,学习异常处理的声明和执行过程

2 实验内容

在《实验十 抽象类》的基础上进行扩展。
(1)在类的层次中添加正方形框架(Square),声明为长方形的子类。为每
类框架定义一个 classId,即圆,1;长方形,2;直角三角形,3;正方形,4。定
义每个框架的单价,单位是 元/厘米。

(2)用一个文本文件(Shapes.txt)存放每类框架的名字及单价(元/厘米),
然后根据文本文件生成框架产品的目录清单,将清单中的产品读取到动态数组中,
然后排序并输出到显示器上。所有框架的几何参数都默认为 3 厘米,即圆的半径
为 3;直角三角形的边长为 3,3;等。

  1. Circle, 4.0
  2. Rectangle, 2.0
  3. RightAngle, 3.5
  4. Square, 1.5

(3)将文本文件中的产品,按其分类,分别存入相应的二进制固定长文件, 即 Circle.dat,Rectangle.dat,Rightrangle.dat 和 Square.dat 中,并再次从文件中读
取出来,按照类别输出到显示器上。固定长文件记录的格式如下:
圆:1 Circle Radius Price
长方形:2 Rectangle Width Height Price

(4)自定义异常类 FileNotFoundException。表示当读取文本文件 Shapes.txt
时,如果在指定的目录中没有找到该文件,就抛出该异常对象。并在程序中适当
的位置处理异常,给出错误提示,并等待用户创建正确的 Shapes.txt 文件。

FileNotFoundException 类要继承 logic_error 类。

源代码

Frame.cpp
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <cmath>
#include <stdexcept>
#include <iomanip>
#include "Array.h"

using namespace std;

class Shape {
public:
	Shape(int classId, double unitPrice) :
			classId(classId), unitPrice(unitPrice) {
	}
	virtual ~Shape() { }
	virtual double getCircumference() = 0;
	virtual void showInfo() = 0;
	bool operator >(Shape & shape);

	int getClassId() {
		return classId;
	}
	double getUnitPrice() const {
		return unitPrice;
	}
	void setUnitPrice(double unitPrice) {
		this->unitPrice = unitPrice;
	}
private:
	int classId;
	double unitPrice;
};

bool Shape::operator >(Shape & shape) {
	return (getCircumference() > shape.getCircumference());
}

class Circle: public Shape {
public:
	Circle(double unitPrice = 0, int classId = 1) :
			Shape(classId, unitPrice) {
	}
	Circle(double radius, double unitPrice, int classId = 1) : // 圆形的classId默认为1
			Shape(classId, unitPrice), radius(radius) {
	}

	static Shape * createCircle() {
		cout << "请输入圆形的半径和单价:";
		double radius, unitPrice;
		cin >> radius >> unitPrice;
		return new Circle(radius, unitPrice);
	}

	double getCircumference() {
		return 2 * radius * PI;
	}

	void showInfo() {
		cout << getClassId() << ". 圆形,半径" << radius << ",周长" << getCircumference() << ", 单价" << getUnitPrice() << endl;
	}

private:
	double radius;
	static const double PI = 3.1415926;
};

class Rectangle: public Shape {
public:
	Rectangle(double unitPrice = 0, int classId = 2) :
			Shape(classId, unitPrice) {
	}
	Rectangle(double length, double width, double unitPrice, int classId = 2) : // 长方形的classId默认为2
			Shape(classId, unitPrice), length(length), width(width) {
	}

	static Shape * createRectangle() {
		cout << "请输入长方形的长、宽和单价:";
		double length, width, unitPrice;
		cin >> length >> width >> unitPrice;
		return new Rectangle(length, width, unitPrice);
	}

	double getCircumference() {
		return 2 * (length + width);
	}

	void showInfo() {
		cout << getClassId() << ". 长方形,长" << length << ",宽" << width << ",周长" << getCircumference() << ", 单价" << getUnitPrice() << endl;
	}

private:
	double length;
	double width;
};

class Square: public Rectangle {
public:
	Square(double unitPrice = 0, int classId = 4) :
			Rectangle(unitPrice, classId) {
	}
	Square(double edge, double unitPrice, int classId = 4) : // 正方形的classId默认为4
			Rectangle(edge, edge, unitPrice, classId), edge(edge) {
	}

	static Shape * createSquare() {
		cout << "请输入正方形的边长和单价:";
		double edge, unitPrice;
		cin >> edge >> unitPrice;
		return new Square(edge, unitPrice);
	}

	void showInfo() {
		cout << getClassId() << ". 正方形,边长" << edge << ",周长" << getCircumference() << ", 单价" << getUnitPrice() << endl;
	}

private:
	double edge;
};

class RightTriangle: public Shape {
public:
	RightTriangle(double unitPrice = 0, int classId = 3) :
			Shape(classId, unitPrice) {
	}
	RightTriangle(double edge1, double edge2, double unitPrice, int classId = 3) : // 直角三角形的classId默认为3
			Shape(classId, unitPrice), edge1(edge1), edge2(edge2) {
	}

	static Shape * createRightTriangle() {
		cout << "请输入直角三角形的两条边长和单价:";
		double edge1, edge2, unitPrice;
		cin >> edge1 >> edge2 >> unitPrice;
		return new RightTriangle(edge1, edge2, unitPrice);
	}

	double getCircumference() {
		return edge1 + edge2 + sqrt(edge1 * edge1 + edge2 * edge2);
	}

	void showInfo() {
		cout << getClassId() << ". 直角三角形,直角边" << edge1 << ",直角边" << edge2 << ",周长" << getCircumference() << ", 单价" << getUnitPrice() << endl;
	}

private:
	double edge1;
	double edge2;
};

class FileNotFoundException: public runtime_error {
public:
	FileNotFoundException(const string &what_arg) : runtime_error(what_arg) {
	}
};

void insertSort(Array<Shape *> &shapes, int index, Shape * ptr) { // 将新创建的形状ptr插入到动态数组shapes中
	int size = shapes.getSize();
	int boundary = 0;

	for (; boundary < index; boundary++) {
		if (*shapes[boundary] > *ptr)
			break;
	}

	for (int i = size - 1; i > boundary; i--)
		shapes[i] = shapes[i - 1];
	shapes[boundary] = ptr;
}

int createShapes(const char * fileName, Array<Shape *> &shapes) {
	int shapeNums = 0;
	int classId;
	int preSize = shapes.getSize();
	const double value = 3.0;
	string line, shapeName;
	double unitPrice;

	cout << "从文件" << fileName << "中读入数据,生成框架产品的目录清单" << endl;

	ifstream fileStream(fileName);

	if (fileStream.rdstate() & ios::failbit) {
		ostringstream message;
		message << "不能打开文件" << fileName << ",请确认文件是否存在";
		throw FileNotFoundException(message.str());
	}

	while (getline(fileStream, line)) { // 从文本文件中读入1行
		istringstream strStream(line);
		Shape *ptr = NULL;

		strStream >> classId;
		string str1, str2;
		strStream >> str1 >> str2 >> unitPrice;
		// 因为每行的形如: 1. Circle, 4.0,语句执行之后,str1的值是".", str2的值是"Circle,", unitPrice的值是4.0
		switch (classId) {
		case 1:
			ptr = new Circle(value, unitPrice);
			break;
		case 2:
			ptr = new Rectangle(value, value, unitPrice);
			break;
		case 3:
			ptr = new RightTriangle(value, value, unitPrice);
			break;
		case 4:
			ptr = new Square(value, unitPrice);
			break;
		default:
			cout << "错误的classId,请检查文件的内容" << endl;
			break;
		}

		insertSort(shapes, shapeNums, ptr); // 执行插入排序
		shapeNums++;

		if (shapeNums >= preSize) { // 调整动态数组的大小
			preSize *= 2;
			shapes.resize(preSize);
		}
	}

	for (int i = 0; i < shapeNums; i++)
		shapes[i]->showInfo();

	return shapeNums;
}

void outputBinaryFiles(Array<Shape *> &shapes, int shapeNums) {
	cout << endl << "将动态数组中的内容分别写入到二进制文件中" << endl;

	ofstream circleFile("Circle.dat", ios_base::out | ios_base::binary);
	ofstream RectangleFile("Rectangle.dat", ios_base::out | ios_base::binary);
	ofstream rightangleFile("Rightangle.dat", ios_base::out | ios_base::binary);
	ofstream squareFile("Square.dat", ios_base::out | ios_base::binary);

	for (int i = 0; i < shapeNums; i++) {
		int classId = shapes[i]->getClassId();
		switch (classId) {
		case 1: {
			Circle *ptr = dynamic_cast<Circle *>(shapes[i]);
			circleFile.write(reinterpret_cast<char *>(ptr), sizeof(*ptr));
			// shapes[i]->showInfo();
			// cout << "size = " << sizeof(*ptr) << endl;
			break;
		}
		case 2: {
			Rectangle *ptr = dynamic_cast<Rectangle *>(shapes[i]);
			RectangleFile.write(reinterpret_cast<char *>(ptr), sizeof(*ptr));
			break;
		}
		case 3: {
			RightTriangle *ptr = dynamic_cast<RightTriangle *>(shapes[i]);
			rightangleFile.write(reinterpret_cast<char *>(ptr), sizeof(*ptr));
			break;
		}
		case 4: {
			Square *ptr = dynamic_cast<Square *>(shapes[i]);
			squareFile.write(reinterpret_cast<char *>(ptr), sizeof(*ptr));
			break;
		}
		}
	}
	circleFile.close();
	cout << "文件写入操作完成" << endl;
}

void readBinaryFiles() {
	cout << endl << "从二进制文件中读取数据" << endl;

	ifstream circleFile("Circle.dat", ios_base::in | ios_base::binary);
	ifstream RectangleFile("Rectangle.dat", ios_base::in | ios_base::binary);
	ifstream rightangleFile("Rightangle.dat", ios_base::in | ios_base::binary);
	ifstream squareFile("Square.dat", ios_base::in | ios_base::binary);

	Circle circle;
	while (circleFile.read(reinterpret_cast<char *>(&circle), sizeof(circle))) {
		//circleFile.read(reinterpret_cast<char *>(&circle), sizeof(circle));
		circle.showInfo();
	}
	circleFile.close();

	Rectangle rectangle;
	while (RectangleFile.read(reinterpret_cast<char *>(&rectangle), sizeof(rectangle))) {
		rectangle.showInfo();
	}
	RectangleFile.close();

	RightTriangle right;
	while (rightangleFile.read(reinterpret_cast<char *>(&right), sizeof(right))) {
		right.showInfo();
	}
	rightangleFile.close();

	Square square;
	while (squareFile.read(reinterpret_cast<char *>(&square), sizeof(square))) {
		square.showInfo();
	}
	squareFile.close();

	cout << "文件读取操作完成" << endl;
}

int main() {
	int preSize = 2; // 动态数组的初始大小
	Array<Shape *> shapes(preSize);
	for (int i = 0; i < preSize; i++) // 要将shapes中的指针元素初始化为NULL,否则有可能是“野指针”
		shapes[i] = NULL;

	int shapeNums = 0;
	try {
		shapeNums = createShapes("Shapes.txt", shapes);
	} catch (FileNotFoundException &e) {
		cout << e.what() << endl;
	}

	outputBinaryFiles(shapes, shapeNums);
	readBinaryFiles();

	return 0;
}

Array.h
//Array.h
#ifndef ARRAY_H
#define ARRAY_H

#include <cassert>
using namespace std;

//数组类模板定义
template <class T> 
class Array {
private:
	T* list;	//T类型指针,用于存放动态分配的数组内存首地址
	int size;	//数组大小(元素个数)
public:
	Array(int sz = 50);			//构造函数
	Array(const Array<T> &a);	//拷贝构造函数
	~Array();	//析构函数
	Array<T> & operator = (const Array<T> &rhs); //重载"="使数组对象可以整体赋值
	T & operator [] (int i);	//重载"[]",使Array对象可以起到C++普通数组的作用
	const T & operator [] (int i) const;	//"[]"运算符的const版本
	operator T * ();	//重载到T*类型的转换,使Array对象可以起到C++普通数组的作用
	operator const T * () const;	//到T*类型转换操作符的const版本
	int getSize() const;	//取数组的大小
	void resize(int sz);	//修改数组的大小
};

//构造函数
template <class T>
Array<T>::Array(int sz) {
	size = sz;	// 将元素个数赋值给变量size
	list = new T [size];	//动态分配size个T类型的元素空间
}

//析构函数
template <class T>
Array<T>::~Array() {
	delete [] list;
}

//拷贝构造函数
template <class T>
Array<T>::Array(const Array<T> &a) {
	//从对象x取得数组大小,并赋值给当前对象的成员
	size = a.size;
	//为对象申请内存并进行出错检查
	list = new T[size];	// 动态分配n个T类型的元素空间
	//从对象X复制数组元素到本对象  
	for (int i = 0; i < size; i++)
		list[i] = a.list[i];
}

//重载"="运算符,将对象rhs赋值给本对象。实现对象之间的整体赋值
template <class T>
Array<T> &Array<T>::operator = (const Array<T>& rhs) {
	if (&rhs != this) {
		//如果本对象中数组大小与rhs不同,则删除数组原有内存,然后重新分配
		if (size != rhs.size) {
			delete [] list;		//删除数组原有内存
			size = rhs.size;	//设置本对象的数组大小
			list = new T[size];	//重新分配n个元素的内存
		}
		//从对象X复制数组元素到本对象  
		for (int i = 0; i < size; i++)
			list[i] = rhs.list[i];
	}
	return *this;	//返回当前对象的引用
}

//重载下标运算符,实现与普通数组一样通过下标访问元素,并且具有越界检查功能
template <class T>
T &Array<T>::operator[] (int n) {
	return list[n];				//返回下标为n的数组元素
}

template <class T>
const T &Array<T>::operator[] (int n) const {
	return list[n];			//返回下标为n的数组元素
}

//重载指针转换运算符,将Array类的对象名转换为T类型的指针,
//指向当前对象中的私有数组。
//因而可以象使用普通数组首地址一样使用Array类的对象名
template <class T>
Array<T>::operator T * () {
	return list;	//返回当前对象中私有数组的首地址
}

template <class T>
Array<T>::operator const T * () const {
	return list;	//返回当前对象中私有数组的首地址
}

//取当前数组的大小
template <class T>
int Array<T>::getSize() const {
	return size;
}

// 将数组大小修改为sz
template <class T>
void Array<T>::resize(int sz) {
	if (sz == size)	//如果指定的大小与原有大小一样,什么也不做
		return;
	T* newList = new T [sz];	//申请新的数组内存
	int n = (sz < size) ? sz : size;	//将sz与size中较小的一个赋值给n
	//将原有数组中前n个元素复制到新数组中
	for (int i = 0; i < n; i++)
		newList[i] = list[i];
	delete[] list;		//删除原数组
	list = newList;	// 使list指向新数组
	size = sz;	//更新size
}
#endif  //ARRAY_H

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值