zoukankan      html  css  js  c++  java
  • c++自定义数组越异常 ArrayIndexOutOfBoundsException (学习)

    #include <iostream>

    using namespace std;

    const int DefaultSize = 10;

    class Array
    {
    public:
      Array(int itsSize=DefaultSize);
      ~Array()
      {
        delete[] pType;
      }

      //运算符重载
      int& operator[](int offset);
      const int& operator[](int offset) const;
      
      int GetItsSize() const
      {
        return itsSize;
      }

      class ArrayIndexOutOfBoundsException {};
      class ElementZero{};

    private:
      int *pType;
      int itsSize;
    };

    Array::Array(int size) :itsSize(size)
    {
      if (size==0)
      {
        throw ElementZero();
      }
      
      pType = new int[size];
      for (int i=0;i<size;i++)
      {
        pType[i] = 0;
      }
    }

    int& Array::operator[](int offset)
    {
      int vcsize =GetItsSize();
      if (offset>=0 && offset<vcsize)
      {
        return pType[offset];
      }else{
        throw ArrayIndexOutOfBoundsException();
      }

    }

    const int& Array::operator[](int offset) const
    {
      int vcsize = this->GetItsSize();
      if (offset >= 0 && offset<vcsize)
      {
        return pType[offset];
      }
      else {
        throw ArrayIndexOutOfBoundsException();
      }
    }

    int main()
    {
      Array a;
      Array b(12);
      b[2] = 10;

      cout << b[2]<< endl;

      Array arr1(20);
      try
      {
        for (int k=0;k<100;k++)
        {
          arr1[k] = k;
        }
      }
      catch (Array::ArrayIndexOutOfBoundsException)
      {
        cout<<"Array Index Out Of Bounds Exception..."<<endl;
      }

      system("pause");
      return 0;
    }

    -------------------------------------------------------------------------------------

    10
    Array Index Out Of Bounds Exception...
    请按任意键继续. . .

  • 相关阅读:
    Elasticsearch核心技术与实战-学习笔记
    在ABP中灵活使用AutoMapper
    使用log4net记录ABP日志
    Abp小知识-如何全局设置DontWrapResult属性
    《C#并发编程经典实例》学习笔记—2.7 避免上下文延续
    NEST 6.X升级到7.X
    django框架——十
    django——自定义分页
    django框架九
    orm数据库查询优化和数据库三大设计范式
  • 原文地址:https://www.cnblogs.com/herd/p/10991214.html
Copyright © 2011-2022 走看看