• 第二十四章 异常和错误处理 4创建异常类的成员函数 简单


    //第二十四章 异常和错误处理 4创建异常类的成员函数
    #include <iostream>
    using namespace std;
    #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()const{ return size;}
    
    	class wrong{};
    	class offset{
    		public:
    			offset(int Size):osize(Size){};
    			~offset(){};
    			int Get(){ return osize;}
    		private:
    			int osize;
    	};
    
    	class Big:public offset{
    	public:
    		Big(int Size):offset(Size){}
    	}; 
    	class Nav:public offset{
    	public:
    		Nav(int Size):offset(Size){}
    	}; 
    	class Small{
    		public:
    			Small(int Size):_size(Size){}
    			~Small(){}
    			int Get(){ return _size;}
    		private:
    			int _size;
    	};
    	class Zero: public Small{
    	public:
    		Zero(int Size):Small(Size){}
    	};
    private:
    	int *p;
    	int size;
    };
    
    people::people(int Size):size(Size)
    {
    	 cout<<"调用构造函数"<<endl;
    	 if(Size == 0){
    		 throw Zero(Size);
    	 }
    	 if(Size < 10){
    	     throw Small(Size);
    	 }
    	 if(Size > 10000){
    	     throw Big(Size);
    	 }
    	 if(Size < 1){
    	     throw Nav(Size);
    	 }
         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();
      	if(off>=0 && off < GetSize())
    	{
    	     return p[off];
    	}
    	throw wrong();
    	return p[0];    
    }
    
    int main()
    {
    	try{
    	    people one(9);
    		for(int i=0; i<100; i++){
    		   one[i] = i;
    		   cout<<"one["<<i<<"]:"<<i<<endl;
    		}
    	}
    	catch(people::wrong){
    	    cout<<"超过数组长度,不能继续进行赋值操作"<<endl;
    	}
    	catch(people::Big big){
    		cout<<"数组值过大,值为:"<<big.Get()<<endl;
    	}
    	catch(people::Small small){
    		cout<<"数组值过小,值为:"<<small.Get()<<endl;
    	}
    	catch(people::Zero zero){
    	     cout<<"下标值为0"<<endl;
    	}
    	catch(people::Nav nav){
    	     cout<<"下标值为负数"<<endl;
    	}
    	catch(people::offset){
    	     cout<<"下标值过大或者过小"<<endl;
    	}
        return 0;
    }
    

      

  • 相关阅读:
    About Dump File
    设置IIS延长Debug
    正则表达式中\d和[00]有什么区别
    理解程序语言语法的merge工具——semanticmerge
    大数据还是小数据
    如何在TFS中配置别的diff/merge的工具
    一个很cool的展示编程语言相互影响关系的网状图
    常见的算法的时间和空间复杂度
    C#的强迫执行域Constrained Execution Regions(CERs)
    C++的C4305和C4800的编译警告
  • 原文地址:https://www.cnblogs.com/xiangxiaodong/p/2719226.html
Copyright © 2020-2023  润新知