考虑以下头文件:

template <typename T> struct tNode
{
    T Data;                      //the data contained within this node
    list<tNode<T>*> SubNodes;       //a list of tNodes pointers under this tNode

    tNode(const T& theData)
    //PRE:  theData is initialized
    //POST: this->data == theData and this->SubNodes have an initial capacity
    //      equal to INIT_CAPACITY, it is set to the head of SubNodes
    {
        this->Data = theData;
        SubNodes(INIT_CAPACITY);   //INIT_CAPACITY is 10
    }

};


现在考虑另一个文件中的一行代码:

list<tNode<T>*>::iterator it();  //iterate through the SubNodes


编译器给我这个错误消息:Tree.h:38:17: error: need ‘typename’ before ‘std::list<tNode<T>*>::iterator’ because ‘std::list<tNode<T>*>’ is a dependent scope

我不知道为什么编译器为此大吼大叫。

最佳答案

list<tNode<T>*>::iterator中,您有一个从属名称,即依赖于模板参数的名称。

因此,编译器无法检查list<tNode<T>*>(此时它没有定义),因此它不知道list<tNode<T>*>::iterator是静态字段还是类型。

在这种情况下,编译器会假定它是一个字段,因此在您的情况下会产生语法错误。要解决此问题,只需在声明前放置typename即可告诉编译器它是一种类型:

typename list<tNode<T>*>::iterator it

10-08 04:08