c++ - 在模板类中声明模板友元类时出现编译器错误

标签 c++ templates compiler-errors friend

出于教学目的,我一直在尝试实现自己的链表类。

我在迭代器声明中将“List”类指定为友元,但它似乎无法编译。

这些是我使用过的 3 个类的接口(interface):

Node.h:

#define null (Node<T> *) 0

template <class T>
class Node {
 public:
    T content;
    Node<T>* next;
    Node<T>* prev;

    Node (const T& _content) :
        content(_content),
        next(null),
        prev(null)
    {}
};

Iterator.h:

#include "Node.h"

template <class T>
class Iterator {
 private:
    Node<T>* current;

    Iterator (Node<T> *);

 public:
    bool isDone () const;

    bool hasNext () const;
    bool hasPrevious () const;
    void stepForward ();
    void stepBackwards ();

    T& currentElement () const;

    friend class List<T>;
};

List.h

#include <stdexcept>
#include "Iterator.h"

template <class T>
class List {
 private:
    Node<T>* head;
    Node<T>* tail;
    unsigned int items;

 public:
    List ();

    List (const List<T>&);
    List& operator = (const List<T>&);

    ~List ();

    bool isEmpty () const {
        return items == 0;
    }
    unsigned int length () const {
        return items;
    } 
    void clear ();

    void add (const T&);
    T remove (const T&) throw (std::length_error&, std::invalid_argument&);

    Iterator<T> createStartIterator () const throw (std::length_error&);
    Iterator<T> createEndIterator () const throw (std::length_error&);
};

这是我一直试图运行的测试程序:

trial.cpp

using namespace std;
#include <iostream>
#include "List/List.cc"

int main ()
{
 List<int> myList;

 for (int i = 1; i <= 10; i++) {
  myList.add(i);
 }

 for (Iterator<int> it = myList.createStartIterator(); !it.isDone(); it.stepForward()) {
  cout << it.currentElement() << endl;
 }

 return 0;
}

当我尝试编译它时,编译器给了我以下错误:

Iterator.h:26:错误:“列表”不是模板

Iterator.h:在“Iterator”的实例化中:

trial.cpp:18:从这里实例化

Iterator.h:12:错误:“结构列表”需要模板参数

List.cc:在成员函数'Iterator List::createStartIterator() const [with T = int]'中:

trial.cpp:18:从这里实例化

Iterator.h:14: 错误:'Iterator::Iterator(Node*) [with T = int]' 是私有(private)的

List.cc:120:错误:在此上下文中

似乎它无法识别 friend 声明。 我哪里做错了?

最佳答案

尝试添加前向声明

template <class T> class List;

Iterator.h 的开头 -- 这可能是您需要允许 Iterator 类中的 friend 声明工作的地方.

关于c++ - 在模板类中声明模板友元类时出现编译器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1993482/

相关文章:

c++ - 在 qt 中切换编译器后出现错误

javascript - Haml中的Javascript注释

c++ - Node 插件编译错误

c++ - 从库函数中调用应用函数是否正确?

c++ - 在 Qt 中使用进度回调的 CopyFileEx

用于将 D3 js v3 迁移到 v4 的 Javascript 编译

c++ - 为什么这个程序不起作用?

image - symfony 4 webpack + encore 在模板中处理图像更多信息

c++ - :C++: Exposing specialized templates only

c++ - msvc 11 仅在某些情况下尊重 C++ 外部模板