//15.3.3模板中的常量
#ifndef TCONST_H_
#define TCONST_H_
#include <assert.h>
#include <iostream>
using namespace std;
template<class T , int size = 100> class mblock //模板的参数可以使用编译器的内置类型,而且可以使用缺省值
{
private:
T array[size];
public:
T& operator[] (int index)
{
assert(index >= 0 && index < size);//使mblock具有边界,我们不能在其边界外索引
return array[index];
}
};
class number
{
private:
float f;
public:
number(float F = 0.0f) : f(F) {}
number& operator=(const number& n)
{
f = n.f;
return *this;
}
operator float() const
{
return f;
}
friend ostream& operator<<(ostream& os , const number& x)//运算符重载也可实现类型转换
{
return os << x.f;
}
};
template<class T , int sz = 20> class holder
{
private:
mblock<T,sz>* np;
public:
holder() : np(0) {}
number& operator[](int i)//holder类与mblock非常的相似,但holder中有一个指向mblock的指针,而不是有一个mblock类型的嵌入对象
{ //该指针并不在holder中初始化,而是在第一次访问的时候初始化
assert(i >= 0 && i < sz);//如果我们在创建大量的对象,却又不立即访问它们,可以用这种技术,节省空间
if ( !np )
np = new mblock<T,sz>;
return np->operator[](i);
}
};
#endif
以上为类声明的头文件
int _tmain(int argc, _TCHAR* argv[])
{
holder<number , 20> H;
for( i = 0 ; i < 20 ; i++ )
H[i] = i;
for( j = 0 ; j < 20 ; j++ )
cout << H[j] << endl;
return 0;
}