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

📄 lt05.cpp

📁 一、教学目的: 能理解C++中运算符重载的需要性
💻 CPP
字号:
//*****************************************
//*****************************************

#include<iostream.h>
#include<string.h>

class String
{
  public:
    String(char*,int);
    
    class Range             //异常类1
    {
      public:
        Range(int j):index(j){}
        int index;
    };
    class Size{};           //异常类2
    
    char&operator[](int k)
    {
      if(0<=k&&k<len)
        return p[k];

      throw Range(k);
    }

    private:
      char * p;
      int len;
      static int max;
};
  int String::max=20;
  
  String::String(char * str,int si)
  {
    if(si<0||max<si)
       throw Size();

    p=new char[si];
    strncpy(p,str,si);
    len=si;
  }

  void g(String&str)
  {
    int num=10;
    for(int n=0;n<num;n++)
      cout<<str[n];
    cout<<endl;
  }

  void f()
  {
   //代码区1
   
   try
  {
    //代码区2
    String s("abcdefghijklmnop",10);
    //String s("abcdefghijklmnopqrstuvwxyz",26);
    g(s); 
  }

  catch(String::Range r)
  {  
    cerr<<"->out of range:"<<r.index<<endl;
    //代码区3
  }

  catch(String::Size)
  {
    cerr<<"size illegal!\n";
  }
  cout<<"The program will be continued here.\n\n";
  
  //代码区4
}

void main()
{
  //代码区5

  f();
  cout<<"These code is not effected by probable exception in f()."<<endl;
}

⌨️ 快捷键说明

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