2015-11-05 71 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