Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 奥斯特雷姆<&书信电报;具有模板类的运算符,无法访问私有成员_C++_Templates_Private_Friend - Fatal编程技术网

C++ 奥斯特雷姆<&书信电报;具有模板类的运算符,无法访问私有成员

C++ 奥斯特雷姆<&书信电报;具有模板类的运算符,无法访问私有成员,c++,templates,private,friend,C++,Templates,Private,Friend,我按照stackoverflow上的说明实现了链表模板类,具体操作如下: template<typename T> class List; template<typename T> std::ostream& operator<<(std::ostream&, const List<T>&); template<typename T> class List { private: struct Item

我按照stackoverflow上的说明实现了链表模板类,具体操作如下:

template<typename T> class List;
template<typename T> std::ostream& operator<<(std::ostream&, const List<T>&);

template<typename T>
class List {
private:
    struct Item {
        T value;
        Item *next;
        Item *prev;

        Item(const T &value, Item *next, Item *prev)
                : value(value), next(next), prev(prev) {
        }
    };

    Item *head;
    Item *tail;
    int size;
public:
    List();    
    ~List();    
    List(const List&) = delete;    
    List& operator=(const List &) = delete;    
    friend std::ostream& operator<< <>(std::ostream&, const List<T>&);
};

template <typename T>
std::ostream& operator<<(std::ostream& os, const List<T>& list) {
    Item* p = list.head;
    while (p != NULL) {
        os << p->value << " ";
        p = p->next;
    }
    return os;
}

我不知道它是如何成为朋友的,所以我应该有权访问所有私人成员,对吗?

作为
列表的每个类模板专门化的成员在全局函数(模板)中找不到
operator
Item
作为
List
的每个类模板专门化的成员,在全局函数(模板)中找不到
operatorfriend声明'std::ostream&operatorYeah,没关系:-列表类型要么是
typename List::Item
,要么你可以说:
(auto p=list.head;p;p=p->next){os-value-friend-declaration'std::ostream&operatorYeah,没关系:-列表类型要么是
typename-list::Item
,要么你可以说:
for(auto p=list.head;p;p=p->next){os value我不确定这是否是您的意思,但我将其添加到实现中,如以下列表::Item*p=List.head;这会导致错误“'p'未在此范围内声明”Hm。我不完全理解您所做的。请参阅我的答案中最近添加的代码块和此实时示例:(我为构造函数和析构函数添加了虚拟实现)很好,谢谢你,这是有效的,但是我不知道如何以及为什么,我从来没有在这种上下文中看到typename关键字。本质上,你需要告诉编译器在类
列表
中搜索name
-因此
列表::项
-你需要告诉它它是一个类型(不是一个变量)通过使用
typename
。我不确定这是否是您的意思,但我将其添加到实现中,如以下列表::Item*p=List.head;这会导致错误“'p'未在此范围内声明”Hm。我不完全理解您所做的。请参阅我的答案中最近添加的代码块和此实时示例:(我为构造函数和析构函数添加了虚拟实现)很好,谢谢你,这是有效的,但是我不知道如何以及为什么,我从来没有在这种上下文中看到typename关键字。本质上,你需要告诉编译器在类
列表
中搜索name
-因此
列表::项
-你需要告诉它它是一个类型(不是一个变量)通过使用
typename
error: 'Item' was not declared in this scope
template <typename T>
std::ostream& operator<<(std::ostream& os, const List<T>& list) {
    typename List<T>::Item* p = list.head; // <- here
    while (p != NULL) {
        os << p->value << " ";
        p = p->next;
    }
    return os;
}