数组类模板

模板参数可以是数值型参数(非类型参数)

在这里插入图片描述

数值型模板参数的限制

  • 变量、浮点数、类对象不能作为模板参数
  • 本质:模板参数是在编译阶段被处理的单元,因此,在编译阶段必须准确无误的唯一确定

1+2+3+ … +N的值?

  • 数值型模板参数
#include <iostream>
#include <string>

using namespace std;
template 
< typename T, int N>
void func()
{
	T a[N] = {0};
	for(int i=0; i<N; i++)
	{
		a[i] = i;
	}
	
	for(int i=0; i<N; i++)
	{
		cout << a[i] << endl;
	}	
	
}

template
< int N >
class Sum
{
public:
	static const int VALUE = Sum<N-1>::VALUE + N;//全局数据区或符号表(值确定), 递归
};

template
< >
class Sum < 1 >
{
public:
	static const int VALUE = 1;
};


int main()
{

	cout << "1+2+3+...+100 = " << Sum<100>::VALUE << endl;//VALUE在编译时已经确定,运行时直接访问此值
	cout << "1+2+3+...+10 = " << Sum<10>::VALUE << endl;
	
    return 0;
}

数组类模板


#ifndef _ARRAY_H_
#define _ARRAY_H_

template
< typename T, int N >
class Array
{
	T m_array[N];
public:
	int length();
	bool set(int index, T value);
	bool get(int index, T& value);//为什么&??
	T& operator[] (int index);
	T operator[] (int index) const;//const 成员函数
	
	virtual ~Array();//为什么用虚函数?
};

template
< typename T, int N >
bool Array<T, N>::set(int index, T value) 
{
	bool ret = (0 <= index) && (index < N);
	if( ret )
	{
		m_array[index] = value;
	}
	return ret;
}

template
< typename T, int N >
bool Array<T, N>::get(int index, T& value)//value用来传递数值的变量别名
{
	bool ret = (0 <= index) && (index < N);
	if( ret )
	{
		value = m_array[index];
	}
	return ret;	
}

template
< typename T, int N >
T& Array<T, N>::operator[] (int index)
{
	return m_array[index];
}

template
< typename T, int N >
T Array<T, N>::operator[] (int index) const//返回的是值而不是引用
{
	return m_array[index];
}


template
< typename T, int N >
Array<T, N>::~Array ()
{
	
}

#endif
#include <iostream>
#include <string>
#include "Array.h"

using namespace std;

int main()
{

	Array<double, 5> ad;
	
	for(int i=0; i<5; i++)
	{
		ad[i] = i*i;
	}
	
	for(int i=0; i<5; i++)
	{
		cout << ad[i] << endl;
	}
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值