码迷,mamicode.com
首页 > 编程语言 > 详细

c++自定义数组越异常 ArrayIndexOutOfBoundsException (学习)

时间:2019-06-08 19:08:49      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:std   fbo   pause   namespace   private   throw   fse   ssi   ace   

#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...
请按任意键继续. . .

 

c++自定义数组越异常 ArrayIndexOutOfBoundsException (学习)

标签:std   fbo   pause   namespace   private   throw   fse   ssi   ace   

原文地址:https://www.cnblogs.com/herd/p/10991214.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!