essential c++ 第六章

1.被参数化的类型

template<typename valtype>
class btnode{
	public:
	
	private:
		valtype _val;
		int _cnt;
		btnode *_lchild;
		btnode *_rchild;
}; 

在class template中,valtype相当于一个占位符,其名称可以任意设定。

为了通过class template实例化类,必须在class template名称之后,紧接一个尖括号,其中放置一个实际的类型。

btnode<int> bti;
btnode<string> bts;

通过int和string来替代valtype这个占位符

在声明玩btnode之后,再声明binarytree 这个class template

template <typename elemtype>
class binarytree{
	public:
	private:
            btnode<elemtype> *_root;  //btnode必须以template 参数列表的形式限定
};

这样才能保证,binarytree的类型和btnode的类型保持一致

2.class template的定义

template <typename elemtype>
class binarytree{
	public:
            binarytree();
            binarytree(const binarytree&);
            ~binarytree();
            binarytree& operator=(const binarytree&);
		
            bool empty() {
                return _root==0;
            }
            void clear();
	private:
            btnode<elemtype> *_root;
            void copy(btnode<elemtype> *tar,btnode<elemtype> *src);
};

在类中定义一个inline函数,其做法和普通的非模板类是一样的,但是在类外,定义的方式不大相同

template <typename elemtype> 
inline binarytree<elemtype>::binarytree:_root(0){
}

也就是在定义class template时,需要先指定template的占位符,然后在声明scope的时候,也需要将占位符体现出来。binarytree<elemtype>::就表示这个函数属于class的定义范围内。

3.template类型参数的处理

在构造函数中,应该在成员初始化列表中为每个类型参数进行初始化,也就是通过typename定义的量。

template<typename valtype>
inline btnode<valtype>::btnode(const valtype &val):_val(val){
    _cnt=1;
    _lchild=_rchild=0;
}

因为如果在构造函数的函数体类定义,如果val是class类型的,那么这个初始化方式可能存在问题。

在上面的程序中,val是通过占位符valtype来定义的,其参数类型不确定,因此最好使用成员初始化列表来进行初始化

4.实现class template

template <typename elemtype>
inline void binarytree<elemtype>::insert(const elemtype &elem){
	if(_root)
		_root=new btnode<elemtype>(elem);
	else 
		_root->insert_value(elem);
} 

new表达式可以分解为两个操作:

1.向程序的空闲空间请求内存,如果分配到足够的空间,就返回一个指针,指向新的对象,如果空间不足,就抛出异常

2.如果第一步成功,并且外界指定了一个初值,这个新对象便会以适当的方式被初始化。

5.output运算符

为binarytree 这个class template定义output运算符

template <typename elemtype>
inline ostream& operator <<(ostream &os,const binarytree<elemtype> &bt){
	os<< "tree: "<<endl;
	return os; 
}

6.常量表达式和默认参数值

template参数并不是非要某种类型,也可以使用常量表达式作为template的参数

template <int len>
class num_sequence{
	num_sequence(int beg_pos=1);
};

template <int len>
class Fibonacci:public num_sequence<len>{
	Fibonacci(int beg_pos=1):num_sequence<len>(beg_pos){
	}
};

其中,int len相当于在类的内部定义了一个变量,也就是在定义类的时候就给出了这个成员变量len。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值