在C++中定义一个模板类,不能正确的定义move函数,
template<class T>
class List{
};
template< class T>
class DoubleLinkList:public List< T >
{
private:
//public:
struct node{
T data;
node *prev, *next;
node( const T &x,node *p = NULL,node *n = NULL)
{
data = x; prev = p; next = n;
}
node(): next(NULL),prev(NULL){}
~node(){}
};
node *head,*tail;
int currentLength;
node *move( int i )const;
//node *move( int i )const
//{
//node *p = head ->next;
//while( i-- ) p = p ->next;
// return p;
// }
public:
DoubleLinkList();
~DoubleLinkList() { clear(); delete head; delete tail; }
void clear();
int length()const { return currentLength; }
void insert( int i,const T &x );
void remove( int i /* = 0 */ );
int search( const T &x )const;
T visit( int i )const { return move(i) -> data; }
void traverse()const;
};
template< class T >
DoubleLinkList< T >::node *DoubleLinkList< T >::move( int i )const//报错,未能识别类型
{
DoubleLinkList< T >::node *p = head ->next;
while( i-- ) p = p ->next;
return p;
}
原因在于编译器不能正确的识别DoubleLinkList< T >::node ,在未定义的情况下,编译器不能识别这是一个类型还是一个名称,
这就必须用typename关键字;如下
template< class T >
typename DoubleLinkList< T >::node *DoubleLinkList< T >::move( int i )const
{
DoubleLinkList< T >::node *p = head ->next;
while( i-- ) p = p ->next;
return p;
}
这样编译器才能正确识别 DoubleLinkList< T >::node为一个类型;
本文探讨了在C++中定义模板类时遇到的问题,特别是在使用嵌套类型时,如何通过typename关键字解决编译器无法正确识别类型的问题。详细解释了在模板类中使用typename关键字的必要性,确保编译器将DoubleLinkList<T>::node识别为一个类型。
533

被折叠的 条评论
为什么被折叠?



