好友模板运算符<<无法访问 class 的保护成员
friend template operator<< can't access protect member of class
我正在尝试重载 << 运算符以便我可以只键入 cout << linkedList
但出于某种原因,我在访问 ListType [=] 中的私有 NodeType<T> head
时遇到问题32=].
重载函数:
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>&);
// ^^^
我正在尝试重载 << 运算符以便我可以只键入 cout << linkedList
但出于某种原因,我在访问 ListType [=] 中的私有 NodeType<T> head
时遇到问题32=].
重载函数:
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>&);
// ^^^