朋友模板operator <<无法访问保护类的成员

问题描述 投票:1回答:1

我正在尝试重载<<运算符,以便我可以只键入cout << linkedList但由于某种原因,我在访问我的ListType类中的私有NodeType<T> head时遇到问题。

重载功能:

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
c++ templates linked-list encapsulation friend
1个回答
1
投票

你的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>&);
//                                                             ^^^
© www.soinside.com 2019 - 2024. All rights reserved.