请教一个关于类模板嵌套类的问题、
c++吧
全部回复
仅看楼主
level 1
187364503 楼主
#include<iostream>
using namespace std;
template<class Type> class List
{
public:
List()
{
first=new LinkNode<Type>;
}
List(const Type& x)
{
first=new LinkNode<Type>(x);
}
LinkNode<Type>* getHead() const
{
return first;
}
LinkNode<Type>* locate(int i) const
{
if(i<0)
return NULL;
LinkNode *current=first;
int k=0;
while(current!=NULL&&k<i)
{
current=current->link;
k++;
}
return current;
}
private:
class LinkNode
{
public:
Type data;
LinkNode<Type> *link;
LinkNode(LinkNode<Type> *ptr=NULL)
{
link=ptr;
}
LinkNode(const Type& item,LinkNode<Type> *ptr=NULL)
{
data=item;
link=ptr;
}
};
LinkNode<Type> *first;
};
int main()
{
List<int> list;
return 0;
}

2011年11月03日 14点11分 1
level 1
187364503 楼主
给出编译错误信息:
\testcin.cpp|17|error: ISO C++ forbids declaration of 'LinkNode' with no type|
\testcin.cpp|17|error: expected ';' before '<' token|
\testcin.cpp|22|error: expected ';' before 'LinkNode'|
\testcin.cpp|22|error: ISO C++ forbids declaration of 'LinkNode' with no type|
\testcin.cpp|22|error: expected ';' before '<' token|
\testcin.cpp|63|error: expected ';' at end of input|
\testcin.cpp|63|error: expected '}' at end of input|
\testcin.cpp||In constructor 'List<Type>::List()':|
\testcin.cpp|10|error: 'first' was not declared in this scope|
\testcin.cpp|10|error: expected type-specifier before 'LinkNode'|
\testcin.cpp|10|error: expected ';' before 'LinkNode'|
\testcin.cpp||In constructor 'List<Type>::List(const Type&)':|
\testcin.cpp|14|error: 'first' was not declared in this scope|
\testcin.cpp|14|error: expected type-specifier before 'LinkNode'|
\testcin.cpp|14|error: expected ';' before 'LinkNode'|
\testcin.cpp|15|error: expected unqualified-id at end of input|
||=== Build finished: 14 errors, 0 warnings ===|

2011年11月03日 14点11分 2
level 1
187364503 楼主
说明:关键就是嵌套类的语法问题,
一、模板类的嵌套类也是模板类,
而且我的模板类的模板形参与外围类的模板形参一样,所以LinkNode类定义的时候就不要声明模板形参了,对不对?
二、如果LinkNode类不作为嵌套类定义,这样的语法是没错误的呀,没理解到LinkNode 为什么 with no type?

2011年11月03日 14点11分 3
level 1
你的代码有两处错误,
第一,不应该在LinkNode定义之前就是用LinkNode类型;
第二,在模板类里嵌套定义的LinkNode类对于List类来说不是模板类,所以使用时只需要实例化List就可以,LinkNode的使用方法:[typename] List<TYPE>::LinkNode,所以在List内部使用LinkNode直接写LinkNode就可以,不需要加尖括号
2011年12月06日 16点12分 4
level 15
第一个有误,class scope内无此限制。
2011年12月07日 00点12分 5
level 1
这个你可以试试能否通过编译
2011年12月07日 05点12分 6
level 1

2011年12月07日 06点12分 8
1