//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
关注
打赏
最近更新
- 深拷贝和浅拷贝的区别(重点)
- 【Vue】走进Vue框架世界
- 【云服务器】项目部署—搭建网站—vue电商后台管理系统
- 【React介绍】 一文带你深入React
- 【React】React组件实例的三大属性之state,props,refs(你学废了吗)
- 【脚手架VueCLI】从零开始,创建一个VUE项目
- 【React】深入理解React组件生命周期----图文详解(含代码)
- 【React】DOM的Diffing算法是什么?以及DOM中key的作用----经典面试题
- 【React】1_使用React脚手架创建项目步骤--------详解(含项目结构说明)
- 【React】2_如何使用react脚手架写一个简单的页面?