21_1.cpp

来自「本文档是(作者:钱能)《C++程序设计教程》课后习题答案。 选题编辑:张朝阳 」· C++ 代码 · 共 57 行

CPP
57
字号
//ch21_1.cpp

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

class String{
public:
  String(char*, int);
	int Length(){ return len; }
  class Range{        //异常类1
  public:
    Range(int j):index(j){}
    int index;
  };
  class Size{};       //异常类2
  class Pastm{};      //异常类3

  char& operator[](int k)
  {
	  if(0<=k && k<len){
      if(p[k]=='m' && k!=len-1 && p[k+1]<='z' && p[k+1]>='a')
				throw Pastm();
			if(k && p[k-1]=='m' && p[k]>='a' && p[k]<='z')
				throw Pastm();
			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=str.Length();
  for(int n=0; n<num; n++)
    cout <<str[n];
  cout <<endl;
}

void f()
{
  //代码区1

⌨️ 快捷键说明

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