2015-11-05 84 views
1

我一直在試圖定義一個使用在類命名空間中聲明的返回類型的類方法:C++「......沒有指定類型」

template<class T, int SIZE> 
class SomeList{ 

public: 

    class SomeListIterator{ 
     //... 
    }; 

    using iterator = SomeListIterator; 

    iterator begin() const; 

}; 

template<class T, int SIZE> 
iterator SomeList<T,SIZE>::begin() const { 
    //... 
} 

當我嘗試編譯代碼,我得到這個錯誤:

Building file: ../SomeList.cpp 
Invoking: GCC C++ Compiler 
g++ -std=c++0x -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"SomeList.d" -MT"SomeList.d" -o "SomeList.o" "../SomeList.cpp" 
../SomeList.cpp:17:1: error: ‘iterator’ does not name a type 
iterator SomeList<T,SIZE>::begin() const { 
^ 
make: *** [SomeList.o] Error 1 

我也試過這樣定義的方法:

template<class T, int SIZE> 
SomeList::iterator SomeList<T,SIZE>::begin() const { 
    //... 
} 

這:

template<class T, int SIZE> 
SomeList<T,SIZE>::iterator SomeList<T,SIZE>::begin() const { 
    //... 
} 

結果:

Building file: ../SomeList.cpp 
Invoking: GCC C++ Compiler 
g++ -std=c++0x -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"SomeList.d" -MT"SomeList.d" -o "SomeList.o" "../SomeList.cpp" 
../SomeList.cpp:17:1: error: invalid use of template-name ‘SomeList’ without an argument list 
SomeList::iterator SomeList<T,SIZE>::begin() const { 
^ 
make: *** [SomeList.o] Error 1 

我在做什麼錯?

+1

'SomeList :: iterator SomeList :: begin()const {' – Lol4t0

回答

6

名稱iterator作用於您的班級,它是一個從屬名稱。爲了使用它,你需要使用範圍操作和typename關鍵字

typename SomeList<T,SIZE>::iterator SomeList<T,SIZE>::begin() const 

Live Example

正如M.M在評論中指出,你也可以使用尾隨返回語法

auto SomeList<T,SIZE>::begin() const -> iterator { 

Live Example

+0

或者,您可以使用追蹤返回類型,這正是爲此發明的原因:'auto SomeList :: begin()const - > iterator'。在這種形式下,返回類型在班級的範圍 –

+0

@ M.M中查找感謝。我忘了那個。我將它添加到答案中。 – NathanOliver

+0

thx,這兩種解決方案都很好。 – RobinW