⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 exceptions.cpp

📁 24学时攻克C++光盘源代码 深入浅出 方便实用
💻 CPP
字号:
 // Listing 24.1 throwing exceptions
 #include <iostream>

 const int DefaultSize = 10;

 // define the exception class
 class xBoundary
 {
 public:
     xBoundary() {}
     ~xBoundary() {}
 private:
 };

 class Array
 {
 public:
     // constructors
     Array(int itsSize = DefaultSize);
     Array(const Array &rhs);
     ~Array() { delete [] pType;}

     // operators
     Array& operator=(const Array&);
     int& operator[](int offSet);
     const int& operator[](int offSet) const;

     // accessors
     int GetitsSize() const { return itsSize; }

     // friend function
     friend std::ostream& operator<< (std::ostream&, const Array&);

 private:
     int *pType;
     int  itsSize;
 };


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


 Array& Array::operator=(const Array &rhs)
 {
     if (this == &rhs)
         return *this;
     delete [] pType;
     itsSize = rhs.GetitsSize();
     pType = new int[itsSize];
     for (int i = 0; i<itsSize; i++)
         pType[i] = rhs[i];
     return *this;
 }

 Array::Array(const Array &rhs)
 {
     itsSize = rhs.GetitsSize();
     pType = new int[itsSize];
     for (int i = 0; i<itsSize; i++)
         pType[i] = rhs[i];
 }


 int& Array::operator[](int offSet)
 {
     int size = GetitsSize();
     if (offSet >= 0 && offSet < size)
         return pType[offSet];
     throw xBoundary();
     return pType[offSet]; // to appease MSC!
 }


 const int& Array::operator[](int offSet) const
 {
     int mysize = GetitsSize();
     if (offSet >= 0 && offSet < mysize)
         return pType[offSet];
     throw xBoundary();
     return pType[offSet]; // to appease MSC!
 }

 std::ostream& operator<< (std::ostream& output,
                           const Array& theArray)
 {
     for (int i = 0; i<theArray.GetitsSize(); i++)
         output << "[" << i << "] " << theArray[i] << std::endl;
     return output;
 }

 int main()
 {
     Array intArray(20);
     try
     {
         for (int j = 0; j< 100; j++)
         {
             intArray[j] = j;
             std::cout << "intArray[" << j
                 << "] okay..." << std::endl;
         }
     }
     catch (xBoundary)
     {
         std::cout << "Unable to process your input!\n";
     }
     std::cout << "Done.\n";
     return 0;
 }

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -