标签: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; }
标签:mes 下标越界 程序崩溃 name 技术分享 警告 c++语言 amp .com
原文地址:http://www.cnblogs.com/lovemi93/p/7577375.html