問題描述
考慮以下頭文件:
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
}
};
現在考慮來自另一個文件的一行代碼:
Now consider a line of code from another file:
list<tNode<T>*>::iterator it(); //iterate through the SubNodes
編譯器給了我這個錯誤信息:Tree.h:38:17: error: need 'typename' before 'std::list<tNode<T>*>::iterator' 因為 'std::list
The compiler is giving me this error message: Tree.h:38:17: error: need ‘typename’ before ‘std::list<tNode<T>*>::iterator’ because ‘std::list<tNode<T>*>’ is a dependent scope
我不知道為什么編譯器會為此對我大喊大叫.
I have no idea why the compiler is yelling at me for this.
推薦答案
在list
中,你有一個依賴名稱,即依賴于模板參數的名稱.
In list<tNode<T>*>::iterator
, you have a dependant name, that is, a name that depends on a template parameter.
因此,編譯器無法檢查 list
(此時它沒有定義),因此它不知道 >list
要么是靜態字段,要么是類型.
As such, the compiler can't inspect list<tNode<T>*>
(it doesn't have its definition at this point) and so it doesn't know whether list<tNode<T>*>::iterator
is either a static field or a type.
在這種情況下,編譯器假定它是一個字段,因此在您的情況下它會產生語法錯誤.要解決這個問題,只需在聲明前放置一個 typename
來告訴編譯器它是一個類型:
In such a situation, the compiler assumes that it is a field, so in your case it yields a syntax error. To solve the issue, just tell the compiler that it is a type by putting a typename
ahead of the declaration:
typename list<tNode<T>*>::iterator it
這篇關于C++ 模板類型名迭代器的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!