您当前的位置: 首页 >  c++

txwtech

暂无认证

  • 3浏览

    0关注

    813博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

cc38a_demo,21days_C++_异常_(2)异常派生-就是继承

txwtech 发布时间:2020-01-21 21:32:05 ,浏览量:3

//cc38a_demo,21days_Cpp_异常_(2)txwtech20200121 //--异常层次结构 //*异常的类-创建自己的异常类 //*异常派生-就是继承 //*异常中的数据:数据成员

//*按引用传递异常 //*->在异常中使用虚函数

//cc38a_demo,21days_Cpp_异常_(2)txwtech20200121
//--异常层次结构
//*异常的类-创建自己的异常类
//*异常派生-就是继承
//*异常中的数据:数据成员

//*按引用传递异常
//*->在异常中使用虚函数

#include 
using namespace std;
const int DefaultSize = 10;
class Array//数组类,类似动态数组vector
{
public:
	Array(int itsSize = DefaultSize);
	~Array() { delete [] pType; }//删除[]数组指针
	//运算符重载
	//下标运算符重载
	int& operator[](int offSet);//非-常函数
	const int& operator[](int offSet) const;//常函数
	//访问器,accessors
	int GetitsSize() const { return itsSize; }
	//做异常类
	class xBoundary {};
	class xSize 
	{
	public:
		xSize() {}
		xSize(int size) :itsSize(size) {}
		~xSize() {};
		int GetSize() { return itsSize; }
	private:
		int itsSize;
	
	};
	//class xZero {};
	//class xNegative {};
	//class xTooSmall {};
	//class xTooBig {};

	//通过继承实现异常的层次结构,好处是什么?得到更详细的异常信息

	class xZero:public xSize 
	{
	public:
		xZero(int size) :xSize(size) {}
	};
	class xNegative :public xSize
	{
	public:
		xNegative(int size) :xSize(size) {}
	};
	class xTooSmall :public xSize 
	{
	public:
		xTooSmall(int size) :xSize(size) {}
	};
	class xTooBig :public xSize 
	{
	public:
		xTooBig(int size) :xSize(size) {}
	};
private:
	int *pType;
	int itsSize;
};
int& Array::operator[](int offset)//非-常函数
{
	int size = this->GetitsSize();
	if (offset >= 0 && offset < size)
		return pType[offset];
	throw xBoundary(); //xBoundary后面记得加括号()
}
const int& Array::operator[](int offset) const//常函数
{
	int size = this->GetitsSize();
	if (offset >= 0 && offset < size)
		return pType[offset];
	//异常类,用着下标操作中
	throw xBoundary(); //xBoundary后面记得加括号()
}
//Array::Array(int size) :itsSize(size) //
//{
//	if (size == 0)
//		throw xZero(); //throw与catch里面的顺序需要一致
//	else if (size < 0)
//		throw xNegative(); //构造函数里面throw与catch里面的顺序需要一致
//	else if (size > 3000)
//		throw xTooBig();
//	else if (size < 10)
//		throw xTooSmall();
//	pType = new int[size];//动态创建数组,放在pType指针
//	for (int i = 0; i < size; i++)
//		pType[i] = 0;
//}
Array::Array(int size) :itsSize(size) //
{
	if (size == 0)
		throw xZero(size); 
	else if (size < 0)
		throw xNegative(size); 
	else if (size > 3000)
		throw xTooBig(size);
	else if (size < 10)
		throw xTooSmall(size);
	pType = new int[size];//动态创建数组,放在pType指针
	for (int i = 0; i < size; i++)
		pType[i] = 0;
}



int main()
{
	Array a;
	
	Array intArray(20);
	



	try
	{
		//Array b(-12);
		//Array b(30000);
		Array b(6);//6            
关注
打赏
1665060526
查看更多评论
0.0810s