C++入門經典-例9.6-有界數組模板,數組下標的越界警告
阿新 • • 發佈:2017-09-23
函數 div esp src temp 找到 應用 獲取 需要
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[128View Code]; 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; }
C++入門經典-例9.6-有界數組模板,數組下標的越界警告