软件设计师2004年5月下午试题6(C++ 数组下班检测)

简介: 试题六  阅读下列说明和C++程序,将应填入__(n)__处的字句写在答题纸的对应栏内.[程序6说明]  C++语言本身不提供对数组下标越界的判断.为了解决这一问题,在程序6中定义了相应的类模板,使得对于任意类型的二维数组,可以在访问数组元素的同时,对行下标和列下标进行越界判断,并给出相应的提示信息...

试题六
  阅读下列说明和C++程序,将应填入__(n)__处的字句写在答题纸的对应栏内.
[程序6说明]
  C++语言本身不提供对数组下标越界的判断.为了解决这一问题,在程序6中定义了相应的类模板,使得对于任意类型的二维数组,可以在访问数组元素的同时,对行下标和列下标进行越界判断,并给出相应的提示信息.
[程序6]
#include <iostream.h>
template <class T> class Array;
template <Class T> class ArrayBody {
 friend class Array<T>;
 T* tpBody;
 int iRows,iColumns,iCurrentRow;
 ArrayBody(int iRsz,int iCsz){
  tpBody = new T[iRsz*iCsz];
  iRows = iRsz;iColumns = iCsz;iCurrentRow = -1:
}
public;
 T& operator[](int j){
  bool row_error,column_error;
  row_error = column_error =false;
  try {
   if(iCurrentRow < 0 || iCurrentRow >= iRows)
    row_error = true;
   if(j<0 || j>= iColumns)
    column_error = true;
   if(row_error == true || column_ error == true)
    throw 'error';
  }
  catch(char){
   if(row_error == true)
    cerr << "行下标越界[" << iCurrentRow << "]";
   if(column_error = true)
    cerr << "列下标越界[" << j << "]";
   cout << "\n";
  }
  return tpBody[iCurrentRow * iColumns + j];
 }
 ~Arraygody(){delete[]tpBody:}
};
template <class T> class Array {
 ArrayBody<T> tBody;
 public;
  ArrayBody<T> & operator[](int i) {
   tBody.iCurrentRow=i;
   return tBody;
  }
 Array(int iRsz,int iCsz):tBody(iRsz,iCsz) { }
 }; 

void main()
{
 Array<int> a1(10,20);
 Array<double> a2(3,5);
 int b1;
 double b2; ·
 b1 = a1[-5][10]; //有越界提示:行下标越界[-5]
 b1 = a1[10][15]; //有越界提示:行下标越界[10]
 b1 = a1[1][4];  //没有越界提示
 b2 = a2[2][6];  //有越界提示:列下标越界[6]
 b2 = a2[10][20]; //有越界提示;行下标越界[10]列下标越界[20]
 b2 = a2[1][4];  //没有越界提示
}

相关文章
|
14天前
|
存储 C++
C++程序中的对象数组
C++程序中的对象数组
19 0
|
19天前
|
存储 算法 编译器
【C++ 字符数组的模板特化】面向字符串的C++模板特化:理解与实践
【C++ 字符数组的模板特化】面向字符串的C++模板特化:理解与实践
62 1
|
11天前
|
存储 C++
C++指针数组
C++指针数组
21 1
|
14天前
|
存储 C++
C++程序数组与指针:深入理解与实践
C++程序数组与指针:深入理解与实践
23 1
|
14天前
|
存储 算法 C++
C++程序一维数组:深入理解与实践
C++程序一维数组:深入理解与实践
23 1
|
7天前
|
存储 C++ 索引
c++数组
c++数组
16 2
|
11天前
|
存储 C++ 索引
C++数组
C++数组
19 0
|
11天前
|
C++
C++ 重载 数组对象输入输出流的实现!!!
C++ 重载 数组对象输入输出流的实现!!!
|
13天前
|
存储 搜索推荐 程序员
C++ 数组
C++ 数组
20 0
|
14天前
|
存储 C++ 索引
C++程序字符数组:深入理解与实践
C++程序字符数组:深入理解与实践
23 2