標籤:mes 下標越界 程式崩潰 name 技術分享 警告 c++語言 amp .com
1:C++語言不能檢查數組下標是否越界,如果下標越界就會造成程式崩潰,而程式員在編輯代碼時很難找到下標越界錯誤。那麼如何能使數組進行下標越界檢測呢?此時可以建立數組模板,在定義模板時對數組的下標進行檢查。
在模板中想要擷取下標值,需要重載數組下標運算子“[]”,重載數組下標運算子後使用模板類執行個體化數組,就可以進行下標越界檢測了。例如:
#include <cassert>
template <class T,int b>
class Array
{
T& operator[] (int sub)
{
assert(sub>=0&&sub<b);
}
}
程式中使用了assert函數來進行警告處理,當下標越界情況發生時就彈出對話方塊進行警告,然後輸出出現錯誤的代碼位置。assert函數需要使用cassert標頭檔。
範例程式碼如下:
// 9.6.cpp : 定義控制台應用程式的進入點。//#include "stdafx.h"#include <iostream>#include <iomanip>#include <cassert>using namespace std;class Date{ int iMonth,iDay,iYear; char Format[128];public: Date(int m=0,int d=0,int y=0) { iMonth=m; iDay=d; iYear=y; } friend ostream& operator<<(ostream& os,const Date t) { cout << "Month: " << t.iMonth << ‘ ‘ ; cout << "Day: " << t.iDay<< ‘ ‘; cout << "Year: " << t.iYear<< ‘ ‘ ; return os; } void Display() { cout << "Month: " << iMonth; cout << "Day: " << iDay; cout << "Year: " << iYear; cout << endl; }};template <class T,int b>class Array{ T elem[b]; public: Array(){} T& operator[] (int sub) { assert(sub>=0&& sub<b); return elem[sub]; } };void main(){ 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(int i=0;i<3;i++) cout << dateArray[i] << endl; Date dt4(10,11,13); dateArray[3] = dt4; //彈出警告 cout << dateArray[3] << endl;}View Code
C++入門經典-例9.6-有界數組模板,數組下標的越界警告