当前位置:编程学习 > C/C++ >>

第16章 模板与泛型编程(8)

16.4.1 类模板成员函数

类模板成员函数的定义具有如下形式:

必须以关键字template开头,后接类的模板形参表。

必须指出它是哪个类的成员。

类名必须包含其模板形参。

1.destroy函数

template<class Type> void Queue<Type>::destroy(){ 
    while(!empty()) 
        pop(); 

template<class Type> void Queue<Type>::destroy(){
 while(!empty())
  pop();
}2. pop函数

template<class Type> void Queue<Type>::pop() 

    QueueItem<Type> p=head; 
    this->head=this->head->next; 
    delete p; 

template<class Type> void Queue<Type>::pop()
{
 QueueItem<Type> p=head;
 this->head=this->head->next;
 delete p;
}3. push函数

template<class Type> void Queue<Type>::push(const Type &p) 

    QueueItem<Type> *pt=new QueueItem<Type>(p); 
    if(empty()) 
        head=tail=pt; 
    else{ 
        this->tail->next=pt; 
        tail=pt; 
    } 

template<class Type> void Queue<Type>::push(const Type &p)
{
 QueueItem<Type> *pt=new QueueItem<Type>(p);
 if(empty())
  head=tail=pt;
 else{
  this->tail->next=pt;
  tail=pt;
 }
}4. copy_elems函数

template <class Type> 
void Queue<Type>::copy_elems(const Queue &orig){ 
    for(QueueItem<Type> *pt=orig.head;pt==0;pt=pt->next) 
    { 
        push(pt->item); 
    } 

template <class Type>
void Queue<Type>::copy_elems(const Queue &orig){
 for(QueueItem<Type> *pt=orig.head;pt==0;pt=pt->next)
 {
  push(pt->item);
 }
}5. 类模板成员函数的实例化

类模板的成员函数本身也是函数模板。像其他任何函数模板一样,需要使用类模板的成员函数产生该成员的实例化。与其他函数模板不同的是,在实例化类模板成员函数的时候,编译器不执行模板实参推断,相反,类模板成员函数的模板形参由调用该函数的对象的类型确定。

6. 何时实例化类和成员

类模板的成员函数只有为程序所用才进行实例化。如果某函数从未使用,则不会实例化该成员函数。

 摘自 xufei96的专栏
 

补充:软件开发 , C++ ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,