操作重载<<作为链接列表中的朋友

时间:2017-10-26 00:49:06

标签: c++ operator-overloading friend

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

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;
}

头:

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);
};

我的问题是为什么我收到以下错误说明&#34; next&#34;仍然受到过载功能的保护?

    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;

它被宣布为朋友,DLList是DLNode的朋友。因为它的朋友类我不能做DLList :: DLNode。有什么我想念的吗?

我的第一个想法是它与我的原型有关但不确定。任何指导将不胜感激。注意,我对istream也有类似的问题但是应该修复另一个。

1 个答案:

答案 0 :(得分:0)

next的{​​{1}}和prev成员是私有的,因此只有DLNode本身及其DLNode s。

错误消息是因为friend的{​​{1}}不是operator<<的{​​{1}}。它是DLList的{​​{1}}。友谊不是继承的。 friendDLNode的{​​{1}},friend的{​​{1}}则不是。{/ p>

DLList DLList中,friend循环中DLNode的测试导致循环无法输出列表的operator<<节点。你根本不需要那个检查,摆脱它。该循环应仅检查DLList operator<<。这将解决逻辑错误,并摆脱编译器错误之一。要摆脱其他错误,请使用公开DLList方法,而不是直接访问&& p->next != NULL

for

修复这些错误后,您的循环仍然无法正确输出。您为tail定义了单独的p,但实际上并未调用它。它需要NULL作为输入,但您将DLNode::next_node()传递给next,而for (DLNode *p = l.head; p != NULL; p = p->next_node()) 会调用operator<<。您需要取消引用DLNode指针才能为const DLNode &调用DLNode*

operator<<