c++ - 朋友模板运算符<< 无法访问保护类成员
问题描述
我正在尝试重载 << 运算符,以便我可以输入,但由于某种原因,我在访问我的 ListType 类中cout << linkedList
的私有时遇到了问题。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
};
节点类型原型:
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>&);
// ^^^
推荐阅读
- java - 用于下载压缩文件夹的 Java 代码
- python - Python 错误与 try-within try-else 块
- javascript - 在javascript ES6中向Object类添加一个方法
- anylogic - 有没有办法记录运输者何时(以及多久)彼此相距一定距离?
- java - 如何解决“无法解决变量问题”
- java - Spring JMS MappingJackson2MessageConverter - 无法处理错误
- c# - 让用户选择对象的名称
- php - 我可以在 PHP 中以“\n”开头的变量中添加双引号吗?
- javascript - React Native,如何将嵌套的 if else 转换为 switch 语句?
- python - Plotly:如何使用 go.Figure 和 go.Scatter 为每个 y 误差条设置单独的颜色?