C++中的有界数组模板

C++语言不能够检测数组下标是否越界,如果越界程序就会崩溃。为了检测数组下标越界检测,建立数组模板,可以完成。

在模板中要想获得下标值,需要重载数组下标运算符“[]”,重载数组下标运算符后使用模板类实例化数组,就可以实现下标越界检测。

例如:

#include<cassert>

template<typename T,int b>

class Array
{
  T& opertor[](int sub)
    {
     assert(sub>0&&sub<b);
    }
};

具体例子如下:

#include <iostream>
#include <cassert>
#include <iomanip>
using namespace std;

class Date
{
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;
	}

	~Date()
	{}
	void Display()
	{
		cout << "Month:" << iMonth;
		cout << "Day:" <<iDay ;
		cout << "Year:" << iYear ;
		cout << endl;
	}

private:
public:
	int iMonth;
	int iDay;
	int iYear;

};


template<typename T,int b>
class Array
{
public:
	Array(){}
	~Array(){}
	T& operator[](int sub)
	{
		assert(sub >= 0 && sub < b);
		return elem[sub];
	}

private:
public:
	T elem[b];

};


int main(int argc, char *argv[])
{
	Array<Date, 3>dateArray;
	Date t1(1, 2, 3);
	Date t2(4, 5, 6);
	Date t3(7, 8, 9);
	dateArray[0] = t1;
	dateArray[1] = t2;
	dateArray[2] = t3;
	for (int i = 0; i < 3;++i)
	{
		cout << dateArray[i] << endl;
	}

	Date t4(10, 11, 12);
	dateArray[3] = t4;
	cout << dateArray[3] << endl;

	cout<<"....."<<endl;
	system("pause");
	return 0;
}

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

花雨仙晨

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值