码迷,mamicode.com
首页 > 编程语言 > 详细

C++入门经典-例9.6-有界数组模板,数组下标的越界警告

时间:2017-09-23 00:07:13      阅读:234      评论:0      收藏:0      [点我收藏+]

标签: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-有界数组模板,数组下标的越界警告

标签:mes   下标越界   程序崩溃   name   技术分享   警告   c++语言   amp   .com   

原文地址:http://www.cnblogs.com/lovemi93/p/7577375.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!