問題描述
考慮以下頭文件:
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
}
};
現(xiàn)在考慮來自另一個(gè)文件的一行代碼:
Now consider a line of code from another file:
list<tNode<T>*>::iterator it(); //iterate through the SubNodes
編譯器給了我這個(gè)錯(cuò)誤信息:Tree.h:38:17: error: need 'typename' before 'std::list<tNode<T>*>::iterator' 因?yàn)?'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
我不知道為什么編譯器會(huì)為此對(duì)我大喊大叫.
I have no idea why the compiler is yelling at me for this.
推薦答案
在list
中,你有一個(gè)依賴名稱,即依賴于模板參數(shù)的名稱.
In list<tNode<T>*>::iterator
, you have a dependant name, that is, a name that depends on a template parameter.
因此,編譯器無法檢查 list
(此時(shí)它沒有定義),因此它不知道 >list
要么是靜態(tài)字段,要么是類型.
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.
在這種情況下,編譯器假定它是一個(gè)字段,因此在您的情況下它會(huì)產(chǎn)生語(yǔ)法錯(cuò)誤.要解決這個(gè)問題,只需在聲明前放置一個(gè) typename
來告訴編譯器它是一個(gè)類型:
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
這篇關(guān)于C++ 模板類型名迭代器的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!