c++ - friend 模板运算符<<无法访问类的保护成员

标签 c++ templates linked-list encapsulation friend

我正在尝试重载 << 运算符,这样我就可以键入 cout << linkedList但出于某种原因,我在访问私有(private) 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;
}

列表类型原型(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

};

节点类型原型(prototype):

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

抛出的错误是

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

error within this context

最佳答案

你的 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>&);
//                                                             ^^^

关于c++ - friend 模板运算符<<无法访问类的保护成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55213407/

相关文章:

c - 链表内存问题

c++ - 向使用 C++ 中的链表实现的有向图(邻接表)添加边

c++ - 错误 c3867,不确定我需要做什么来修复

c++ - 无效的模板实例和元程序编译正常?

c++ - 检查已经运行的进程和通信拷贝

c++ - 如何将非常量 int 作为模板参数传递?

c++ - C 到 C++ 转换器

c++ - global operator 一定要写的很具体,不然链接不上

c++ - SFINAE 函数根据模板类型返回正确的字符编码?

c++ - 用C++打印循环链表?