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

找了好就终于找到错误原因。

 

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

 

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

 

#include #include template class List { public: typedef unsigned size_type; public: List(); void push_back(const Type &value); void push_front(const Type &value); Type& front() const; Type& back() const; size_type size() const; ~List(); private: struct DataType { Type Value; struct DataType *next; }head; struct DataType *end; }; template List::List() { head.next = 0; end = &head; } template void List::push_back(const Type &value) { DataType *tmp = new DataType; tmp->Value = value; tmp->next = 0; end->next = tmp; end = tmp; } template void List::push_front(const Type &value) { DataType *tmp = new DataType; tmp->Value = value; tmp->next = 0; tmp->next = head.next; head.next = tmp; } template Type& List::front() const { return head.next->Value; } template Type& List::back() const { return end->Value; } template typename List::size_type List::size() const { size_type iSize = 0; struct DataType *begin = &head; while (begin->next) { ++iSize; } return iSize; } template List::~List() { struct DataType *tmp = &head; while (tmp = tmp->next) { head.next = tmp->next; free(tmp); tmp = &head; } } int main() { List list; list.push_back(100); list.push_front(200); std::cout << list.front() << "/t" << list.back() << std::endl; system("pause"); return 0; }

你可能感兴趣的:(struct,list)