简体   繁体   中英

friend template operator<< can't access protect member of class

I'm trying to overload the << operator so that I can just type cout << linkedList but for some reason, I am having a problem with accessing a private NodeType<T> head in my ListType class.

Overloading Function:

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 Prototype :

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 prototype :

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

The error that is thrown is

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

and

error within this context

Your friend declaration doesn't match the declaration of operator << . Change

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

to

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM