模板类中的成员函数定义返回值为类中的typedef类型时候注意

如果模板类中的成员要访问类中的typedef类型必须加上关键字typename来指明它是一个类型。

 

如一下代码中的那个成员函数size。

 

[cpp]  view plain copy
  1. #include <iostream>  
  2. #include <string>  
  3.   
  4. template<typename Type>  
  5. class List  
  6. {  
  7. public:  
  8.     typedef unsigned size_type;  
  9. public:  
  10.     List();  
  11.     void push_back(const Type &value);  
  12.     void push_front(const Type &value);  
  13.     Type& front() const;  
  14.     Type& back() const;  
  15.     size_type size() const;  
  16.     ~List();  
  17. private:  
  18.     struct DataType  
  19.     {  
  20.         Type Value;  
  21.         struct DataType *next;  
  22.     }head;  
  23.     struct DataType *end;  
  24. };  
  25.   
  26. template<typename Type>  
  27. List<Type>::List()  
  28. {  
  29.     head.next = 0;  
  30.     end = &head;  
  31. }  
  32.   
  33. template<typename Type>  
  34. void List<Type>::push_back(const Type &value)  
  35. {  
  36.     DataType *tmp = new DataType;  
  37.     tmp->Value = value;  
  38.     tmp->next = 0;  
  39.     end->next = tmp;  
  40.     end = tmp;  
  41. }  
  42.   
  43. template<typename Type>  
  44. void List<Type>::push_front(const Type &value)  
  45. {  
  46.     DataType *tmp = new DataType;  
  47.     tmp->Value = value;  
  48.     tmp->next = 0;  
  49.     tmp->next = head.next;  
  50.     head.next = tmp;  
  51. }  
  52.   
  53. template<typename Type>  
  54. Type& List<Type>::front() const  
  55. {  
  56.     return head.next->Value;  
  57. }  
  58.   
  59. template<typename Type>  
  60. Type& List<Type>::back() const  
  61. {  
  62.     return end->Value;  
  63. }  
  64.   
  65. template<typename Type>  
  66. typename List<Type>::size_type List<Type>::size() const  
  67. {  
  68.     size_type iSize = 0;  
  69.     struct DataType *begin = &head;  
  70.   
  71.     while (begin->next)  
  72.     {  
  73.         ++iSize;  
  74.     }  
  75.   
  76.     return iSize;  
  77. }  
  78.   
  79. template<typename Type>  
  80. List<Type>::~List()  
  81. {  
  82.     struct DataType *tmp = &head;  
  83.       
  84.     while (tmp = tmp->next)  
  85.     {  
  86.         head.next = tmp->next;  
  87.         free(tmp);  
  88.         tmp = &head;  
  89.     }  
  90. }  
  91.   
  92. int main()  
  93. {  
  94.     List<int> list;  
  95.     list.push_back(100);  
  96.     list.push_front(200);  
  97.     std::cout << list.front() << "/t" << list.back() << std::endl;  
  98.   
  99.     system("pause");  
  100.     return 0;  
  101. }  

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值