оператор шаблона друга << не может получить доступ к защищенному члену класса - PullRequest
1 голос
/ 18 марта 2019

Я пытаюсь перегрузить оператор <<, чтобы я мог просто набрать <code>cout << linkedList, но по какой-то причине у меня возникла проблема с доступом к частному NodeType<T> head в моем классе ListType.

Функция перегрузки:

template <class U>
std::ostream& operator << (std::ostream& out, const ListType<U>& list) {
    if(list.size() > 0) {
        NodeType<U>* temp = list.head;
        out << temp -> info;
        temp = temp -> link;
        while(temp != NULL) {
            out << ", " << temp -> info;
            temp=temp -> link;
        }
    }
    return out;
}

Прототип ListType:

template <class T>
class ListType {
protected:
    NodeType<T>* head;
    size_t count;

public:
    ListType(); //DONE
    ListType(const ListType&); // DONE
    virtual ~ListType(); //DONE
    const ListType& operator = (const ListType&); //DONE
    virtual bool insert(const T&)=0; //DONE
    virtual void eraseAll(); //DONE
    void erase(const T&); //DONE
    bool find(const T&);
    size_t size() const; //DONE
    bool empty() const;//DONE
private:
    void destroy();//DONE
    void copy(const ListType&);//DONE
    template <class U>
    friend std::ostream& operator << (std::ostream&, const ListType&); //DONE

};

Прототип NodeType:

template <class T>
class NodeType {
public:
    T info;
    NodeType* link;
};

Выдается ошибка

NodeType<int>* ListType<int>::head is protected

и

error within this context

1 Ответ

1 голос
/ 18 марта 2019

Ваша декларация friend не соответствует декларации operator <<. Изменить

template <class U>
friend std::ostream& operator << (std::ostream&, const ListType&);

до

template <class U>
friend std::ostream& operator << (std::ostream&, const ListType<U>&);
//                                                             ^^^
...