当前位置: 移动技术网 > IT编程>开发语言>C/C++ > c/c++ 类模板初探

c/c++ 类模板初探

2018年08月21日  | 移动技术网IT编程  | 我要评论

网游之无法无天,幼年记事簿txt,君主的太阳

类模板

1,模板类里的函数都是模板函数

2,模板类里的函数,在类外面实现的时候,要用模板函数(方法:push_back)的方式实现,在类内部实现时,不需要用模板函数(方法:show)方式实现。

3,用模板类实现单链表,类list是类listnode的友元类;用友元函数重载了类value的<<函数;显示链表的show方法在类外面定义的部分注释掉了。

4,在gcc4.8.5-20下,如果把listnode和list的声明放到.h文件,把实现放在.cpp后,编译无法通过。但是把listnode和list的声明和实现都放到.h文件,就可以编译通过。

编译方法:g++ -g template_main.cpp

============分割线==========================

下面的例子,为了简单起见,都放到了一个cpp文件了。

#include <iostream>
using namespace std;

template<typename a>
class list;

//节点                                                          
template<typename a>
class listnode{
  friend class list<a>;
public:
  listnode():data(a()), next(null){}
  listnode(a a, listnode *n) : data(a), next(n){}
private:
  a data;
  listnode *next;
};

//单链表                                                        
template<typename a>
class list{
public:
  list();
  //尾插                                                        
  bool push_back(a val);
  //显示链表                                                    
  void show()const{
    listnode<a> *n = first->next;
    while(null != n){
      cout << n->data;
      n = n->next;
    }
    cout << "null" << endl;
  }
private:
  listnode<a> *first;
  listnode<a> *last;
  size_t size;
};

template<typename t>
list<t>::list(){
  first = last = new listnode<t>;
  last->next = null;
  size = 0;
}
//尾插                                                          
template<typename a>
bool list<a>::push_back(a value){
  listnode<a> *node = new listnode<a>;
  if(null == node) return false;
  node->data = value;
  node->next = null;

  last->next = node;
  last = node;
  size++;

  return true;
}
//显示链表                                                      
/*                                                              
template<typename a>                                            
void list<a>::show()const{                                      
  listnode<a> *n = first->next;                                 
  while(null != n){                                             
    cout << n->data;                                            
    n = n->next;                                                
  }                                                             
  cout << "null" << endl;                                       
}                                                               
*/
class value{
  friend ostream& operator<<(ostream &o, const value &v);
public:
  value(int d = 0) : value(d){}
private:
  int value;
};
ostream& operator<<(ostream &o, const value &v){
  o << v.value << "->";
  return o;
}

int main(){
  list<value> l;
  for(int i = 0; i < 10; ++i){
    l.push_back(value(i));
  }
  l.show();
}

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网