ArrayTemplate

本文介绍了一个使用C++模板实现的固定大小数组类。该类支持两种构造函数:一种用于初始化数组元素为递增序列;另一种则允许用户指定所有元素的初始值。此外,还提供了下标运算符重载及显示数组内容的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
using namespace std;
template<class ElementType,int n>
class ArrayTemplate
{
public:
 ArrayTemplate();
 ArrayTemplate(const ElementType &t);
 ElementType& operator[](int i);
 void show();
private:
 ElementType a[n];
};
template<class ElementType,int n>
ArrayTemplate<ElementType,n>::ArrayTemplate()
{
 cout<<"执行不带参数的构造函数\n";
 for (int i=0;i<n;i++)
 {
  a[i]=(i+1);
 }
}
template<class ElementType,int n>
ArrayTemplate<ElementType,n>::ArrayTemplate(const ElementType &t)
{
 cout<<"执行带一个参数的构造函数\n";
 for (int i=0;i<n;i++)
 {
  a[i]=t;
 }
}
template<class ElementType,int n>
ElementType& ArrayTemplate<ElementType,n>::operator[](int i)
{
 cout<<"执行下标运算符函数operator[]\n";
 if (i<0||i>=n)
 {
  cout<<"超出数组的限制,程序终止!\n";
  exit(EXIT_FAILURE);
 }
 return a[i];
}
template<class ElementType,int n>
void ArrayTemplate<ElementType,n>::show()
{
 for(int i=0;i<n;i++)
 {
  cout<<"a["<<i<<"]="<<a[i]<<"\t";
 }
 cout<<endl;
}
int main()
{
 ArrayTemplate<int,4>array_1;
 array_1.show();
 ArrayTemplate<int,4>*array_2=new ArrayTemplate<int,4>[4];
 for(int i=0;i<9;i++)
 {
  array_2[i]=array_1[i];
  array_2[i].show();  
 }
 return 0;
}

转载于:https://www.cnblogs.com/greencolor/archive/2013/02/02/2890451.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值