1:c++ language can not check array subscript is out of bounds, if the subscript out of bounds will cause the program to crash, and the programmer in the editing code is difficult to find subscript out of bounds error. So how can you make an array subscript out-of-bounds detection? You can create an array template to check the subscript of the group when you define the template.
In the template you want to get the subscript value, you need to overload the array subscript operator "[]", the overloaded array subscript operator after using the template class instantiation of the array, you can subscript out of bounds detection. For example:
#include <cassert>
Template <class T,int b>
Class Array
{
t& operator[] (int sub)
{
ASSERT (SUB>=0&&SUB<B);
}
}
The Assert function is used in the program for warning processing, and a popup dialog box warns you when the current label is out of bounds, and then prints the location of the code where the error occurred. The Assert function requires the use of the Cassert header file.
The sample code is as follows:
//9.6.cpp: Defines the entry point of the console application. //#include"stdafx.h"#include<iostream>#include<iomanip>#include<cassert>using namespacestd;classdate{intimonth,iday,iyear; Charformat[ -]; Public: Date (intm=0,intD=0,inty=0) {Imonth=m; Iday=D; Iyear=y; } Friend Ostream&operator<< (ostream& OS,ConstDate T) {cout<<"Month:"<< T.imonth <<' ' ; cout<<"Day :"<< t.iday<<' '; cout<<"Year :"<< t.iyear<<' ' ; returnOS; } voidDisplay () {cout<<"Month:"<<Imonth; cout<<"Day :"<<Iday; cout<<"Year :"<<iyear; cout<<Endl; }};template<classTintB>classarray{T Elem[b]; Public: Array () {} T&operator[] (intsub) {Assert (Sub>=0&& sub<b); returnElem[sub]; } };voidMain () {Array<date,3>Datearray; Date DT1 (1,2,3); Date DT2 (4,5,6); Date DT3 (7,8,9); datearray[0]=dt1; datearray[1]=DT2; datearray[2]=DT3; for(intI=0;i<3; i++) cout<< Datearray[i] <<Endl; Date Dt4 (Ten, One, -); datearray[3] = DT4;//pop-up warningcout << datearray[3] <<Endl;}
View Code
Introduction to C + + Classic-Example 9.6-bounded array template, array subscript out of bounds warning