C++入門經典-例9.6-有界數組模板,數組下標的越界警告

來源:互聯網
上載者:User

標籤: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-有界數組模板,數組下標的越界警告

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.