// 第二十四章 异常和错误处理 3异常的派生
#include <iostream>
using namespace std;
const int num=5;
class people
{
public:
people(int Size=num);
~people(){ delete []p; };
int&operator[](int off);
const int&operator[](int off)const;
//int GetSize(){ return size; }
int GetSize()const{ return size;}
class wrong{};
class offset{};
//class Big:public offset{};
//class Nav:public offset{};
class Big{};
class Nav{};
class Small{};
class Zero{};
private:
int *p;
int size;
};
people::people(int Size):size(Size)
{
cout<<"调用构造函数"<<endl;
if(Size == 0){
throw Zero();
}
if(Size < 10){
throw Small();
}
if(Size > 10000){
throw Big();
}
if(Size < 1){
throw Nav();
}
p = new int[Size];
for(int i=0; i<Size; i++)
{
p[i] = 0;
}
}
int&people::operator[](int off)
{
if(off>=0 && off < GetSize())
{
return p[off];
}
throw wrong();
return p[0];
}
//一样,只是该函数内的值是不可更改并且返回值也是不可更改的
const int&people::operator[](int off)const
{
int Size = GetSize();
//这里还是没有太消化得了,const int&people::operator[](int off)const
//在该函数内为什么调用的GetSize()函数声明方式一定要是int GetSize()cosnt{ return size;}
//如果是int GetSize(){ return size;}
//error C2662: “people::GetSize”: 不能将“this”指针从“const people”转换为“people &”
//从这句错误语句可以理解一点
//本方法内用的people是用的const people,也就是对people只能可读操作
//还是弄不太懂
if(off>=0 && off < GetSize())
{
return p[off];
}
throw wrong();
return p[0];
}
int main()
{
try{
people one(-2);
for(int i=0; i<100; i++){
one[i] = i;
cout<<"one["<<i<<"]赋值完毕....."<<endl;
}
}catch(people::wrong){
cout<<"超过数组长度,不能继承执行赋值操作"<<endl;
}
catch(people::offset)
{
cout<<"下标值过大或者为负数"<<endl;
}
catch(people::Big)
{
cout<<"下标值过大"<<endl;
}
catch(people::Small){
cout<<"下标值过小"<<endl;
}
catch(people::Zero){
cout<<"下标值为0"<<endl;
}
catch(people::Nav){
cout<<"下标值为负数"<<endl;
}
return 0;
}