簡體   English   中英

模板和嵌套類/結構

[英]Templates and nested classes/structures

我有一個簡單的容器:

template <class nodeType> list {
    public:
        struct node {
            nodeType info;
            node* next;
        };

    //...
};

現在,有一個名為_search的函數,它搜索列表並返回對匹配的節點的引用。 現在,當我指的是函數的返回類型時,我認為它應該是list<nodeType>::node* 這是正確的嗎? 當我定義函數內聯時,它完美地工作:

template <class nodeType> list {
    public:
        struct node {
            nodeType info;
            node* next;
        };

        node* _search {
            node* temp;
            // search for the node
            return temp;
        }
};

但是,如果我在課外定義函數,

template <class nodeType> list<nodeType>::node* list<nodeType>::_search() {
    //function
}

它不起作用。 編譯器Expected constructor before list<nodeType>::_search給出了一個錯誤,說明了Expected constructor before list<nodeType>::_search 錯誤與此類似。 我目前沒有可以測試它的機器。

任何幫助都是真誠的感謝。

那是因為node是一個依賴類型。 您需要按如下方式編寫簽名(請注意,為了清楚起見,我已將其分為2行)

template <class nodeType> 
typename list<nodeType>::node* list<nodeType>::_search() 
{
    //function
}

請注意使用typename關鍵字。

您需要告訴編譯器node是使用關鍵字typename的類型。否則,它會將節點視為class liststatic變量。 每當在節點實現中使用節點作為類型時, typename添加typename

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM