我目前正在尝试学习如何实现双链表。我有节点的基础,但实际上无法使我的程序与重载运算符一起使用。

DLList.cxx:

ostream& operator<<(ostream &os, const DLList &l) {


DLNode *p;


for (p = l.head; p != NULL && p -> next != NULL; p = p -> next)
{
    os << l;
}
return os;
}

header :
class DLNode
{
private:
int data;
DLNode *prev, *next;

public:
DLNode()
{
    next = prev = NULL;
}

DLNode(int d, DLNode *p=NULL, DLNode *n=NULL)
{
    data = d;
    prev = p;
    next = n;
}

DLNode* next_node() {
    return next;
}

DLNode* prev_node() {
    return prev;
}

friend ostream& operator<< (ostream& os, const DLNode& n) {
    os << n.data;
    return os;
}

friend class DLList;
};



// ADT for Doubly Linked List
class DLList
{
private:
DLNode *head, *tail;

public:

DLList();
~DLList();

bool isEmpty();       // is this list empty?
bool isInList(int);   // is this list contain the given integer?

void addToHead(int);  // add the given integer to the head
void addToTail(int);  // add the given integer to the tail


// DO NOT call this method on empty list
int deleteHead();


// DO NOT call this method on empty list
int deleteTail();


void removeAll();


// append the given list at the end of this list
void append(const DLList& dll);


// output each elemen t in this list to 'os'
friend ostream& operator<< (ostream& os, const DLList& l);


// read an integer from 'is'
// and add it to the tail of this list
friend istream& operator>> (istream& is, DLList& l);
};

我的问题是,为什么我得到以下错误,指出“next”仍受重载函数的保护?
    In function 'std::ostream& operator<<(std::ostream&, const DLList&)':
DLList.cpp:90:40: error: 'DLNode* DLNode::next' is private within this context
for (p = l.head; p != NULL && p -> next != NULL; p = p -> next){
                                    ^~~~
DLList.h:33:20: note: declared private here
 DLNode *prev, *next;
                ^~~~
DLList.cpp:90:63: error: 'DLNode* DLNode::next' is private within this context
 for (p = l.head; p != NULL && p -> next != NULL; p = p -> next){
                                                           ^~~~
DLList.h:33:20: note: declared private here
 DLNode *prev, *next;

它被宣布为 friend ,而DLList是DLNode的 friend 。而且因为它是Friend类,所以我不能执行DLList::DLNode。我有什么想念的吗?

我最初的想法是它与我的原型(prototype)有关,但不确定。任何指导将不胜感激。请注意,我对istream也有类似的问题,但是一个应该解决另一个问题。

最佳答案

nextprevDLNode成员是私有(private)的,因此DLNode本身及其friend只能访问它们。

错误消息是因为您的operator<<DLList不是friendDLNode。而是friendDLList。友谊不是继承的。 DLListfriendDLNode,但operator<<DLList不是。

operator<<DLList中,对&& p->next != NULL循环中的for进行测试会使该循环不输出列表的tail节点。您根本不需要该检查,将其删除。该循环应仅检查p中的NULL。这样可以修复逻辑错误,并摆脱编译器错误之一。要摆脱其他错误,请使用公共(public)DLNode::next_node()方法,而不是直接访问next:

for (DLNode *p = l.head; p != NULL; p = p->next_node())

修复这些错误后,循环仍将无法正确输出。您为operator<<定义了单独的DLNode,但实际上并未调用它。它需要一个const DLNode &作为输入,但是您正在将DLNode*传递给operator<<,它将改为调用std::ostream::operator<<(void*)。您需要取消引用DLNode*指针才能为operator<<调用DLNode:
os << *l;

09-07 09:13