zoukankan      html  css  js  c++  java
  • 134.异常类的处理

    • 异常类
       1 #pragma once
       2 #include <initializer_list>
       3 using namespace std;
       4 
       5 class memerror
       6 {
       7 };
       8 
       9 class outerror
      10 {
      11 };
      12 
      13 class safeintarray
      14 {
      15 private:
      16     int *p;
      17     int n;
      18 
      19 public:
      20     safeintarray(int length);
      21     safeintarray(initializer_list<int> mylist);
      22     safeintarray();
      23     int &operator [](int num);
      24     ~safeintarray();
      25 };
    •  1 #include "safeintarray.h"
       2 
       3 
       4 
       5 safeintarray::safeintarray(int length)
       6 {
       7     if (length <= 0)
       8     {
       9         throw memerror();
      10     }
      11     this->p = new int[length] {0};
      12     this->n = length;
      13 }
      14 
      15 safeintarray::safeintarray(initializer_list<int> mylist)
      16 {
      17 }
      18 
      19 safeintarray::safeintarray()
      20 {
      21 }
      22 
      23 int & safeintarray::operator[] (int num)
      24 {
      25     // TODO: 在此处插入 return 语句
      26     if (num<0 || num>this->n - 1)
      27     {
      28         throw outerror();
      29     }
      30 
      31     return this->p[num];
      32 }
      33 
      34 
      35 safeintarray::~safeintarray()
      36 {
      37 }
    • main.cpp
       1 #include <iostream>
       2 #include "safeintarray.h"
       3 using namespace std;
       4 
       5 void main()
       6 {
       7     try
       8     {
       9         safeintarray s1(5);
      10 
      11         cout << s1[5] << endl;
      12     }
      13     catch(outerror e)
      14     {
      15         cout << "内存分配错误" << endl;
      16     }
      17     catch (memerror e)
      18     {
      19         cout << "越界" << endl;
      20     }
      21 
      22     cin.get();
      23 }
  • 相关阅读:
    Redis的发布订阅
    Redis的事物
    Redis的持久化
    Redis配置文件详解
    Redis五大数据类型
    Redis安装
    DP练习题回顾
    基环树浅谈
    Tarjan算法浅谈
    拓展欧拉定理浅谈
  • 原文地址:https://www.cnblogs.com/xiaochi/p/8686100.html
Copyright © 2011-2022 走看看