c++ - 在模板类中引用下一个类,gettng error "expected ' ;'"

标签 c++

我在尝试编译下面的代码时得到以下信息:

preallocarray.h: In member function 'void PreallocArray<T>::push_back(const T&)':
preallocarray.h:82: error: expected `;' before 'itr'

我在我创建的 LinkedList 类中有一个嵌套的 const_iterator 类。我用 C++ 已经很多年了,所以这可能是由一些愚蠢的事情引起的,但我一直在四处乱逛,在谷歌上搜索了一个小时,但没有运气……

这是我的链表类定义,在 linklist.h 中声明:

template <typename T> 
class LinkedList 
{
    <snip...>
    public:
        class const_iterator
        {
        <snip...>
        };
    <snip...>
};

然后我有第二个类,声明在preallocarray.h中,如下:

#include "linklist.h"
template <typename T>
class PreallocArray
{
    <snip...>
    public:
        void push_back( const T & newValue )
        {
            if (capacity == size)
            {
                allocateNode( capacity / 2 );
            }
            LinkedList<Node>::const_iterator itr; // error occurs here
            theList.end();
        }
    <snip...>

    private:
        LinkedList<Node> theList; // the linked list of nodes
    <snip...>
};

最佳答案

LinkedList<Node>::const_iterator itr; // error occurs here

基于封闭类实际上是类模板这一事实,我怀疑您打算编写T 而不是Node。顺便问一下,Node 是什么?它在哪里定义的?

如果你真的想写T,那么你必须把它写成:

typename LinkedList<T>::const_iterator itr; 

不要忘记像我上面写的那样写typename。如果您必须编写 typename,即使模板参数是 Node 但它的定义在某种程度上取决于 T:

typename LinkedList<Node>::const_iterator itr;//if Node depends on T

要了解为什么需要 typename,请参阅 @Johannes Schaub 的回答:

关于c++ - 在模板类中引用下一个类,gettng error "expected ' ;'",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6403329/

相关文章:

c++ - PySide 中的多线程 Boost Python C++ 代码

c++ - 警告 : ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]

c++ - 为什么 require 子句中的否定表达式需要括号?

c++ - 如何将可变成员函数绑定(bind)到仿函数?

c++ - 在同一解决方案中的项目之间传递 CString

c++ - 弱链接与使用 COMDAT 部分有什么区别?

c++ - 从基类指针调用派生类方法

c++ - 引用是否被视为 C++ 中的指针

c++ - boost::asio io_service 保留我的其余代码运行

c# - 使用MediaCapture进行实时流式传输