【发布时间】:2018-10-23 01:03:36
【问题描述】:
我认为当一个类声明一个朋友类时,朋友可以访问声明者的私有成员?好像不是这样,或者我做错了什么。我正在尝试访问 OULinkedList 中的“第一个”或“最后一个”。当我尝试使用“第一个”或“最后一个”时,我收到“未在此范围内声明”错误。
我需要访问“first”,因为没有它,我的下一个函数将永远不会返回链表的第一个值,而且我不知道该怎么做。
例如,如果我只想打印出列表中的对象,那么下面的 while 循环总是会跳过第一个对象。
while(enumerator.hasNext()){
cout << enumerator.next();
}
这显然不是我想要的。
#include "OULink.h"
#include "Comparator.h"
#include "OULinkedListEnumerator.h"
// OULinkedList stands for Ordered, Unique Linked List. It is a linked list that is always maintained in
// order (based on the comparator provided to it when the list is created) and that only contains unique
// items (that is, duplicates are not allowed)
template <typename T>
class OULinkedList {
template <typename F>
friend class OULinkedListEnumerator;
private:
Comparator<T>* comparator = NULL; // used to determine list order and item equality
unsigned long size = 0; // actual number of items currently in list
OULink<T>* first = NULL; // pointer to first link in list
OULink<T>* last = NULL;
template <typename T>
class OULinkedListEnumerator : public Enumerator<T>
{
private:
OULink<T>* current;
int firstNode = 0;
public:
OULinkedListEnumerator(OULink<T>* first);
bool hasNext() const;
T next();
T peek() const;
};
// Implementation goes here
template<typename T>
OULinkedListEnumerator<T>::OULinkedListEnumerator(OULink<T>* first){
this->current = first;
}
template<typename T>
bool OULinkedListEnumerator<T>::hasNext() const{
if(this->current->next != NULL){
return true;
}else{
return false;
}
}
template<typename T>
T OULinkedListEnumerator<T>::next(){
T successorNode = *this->current->next->data;
this->current = this->current->next;
return successorNode;
}
template<typename T>
T OULinkedListEnumerator<T>::peek() const{
if(current != NULL){
return *current->data;
}else{
throw new ExceptionLinkedListAccess;
}
}
【问题讨论】:
-
相关甚至是骗子:stackoverflow.com/questions/28307374/friend-class-not-working,但 +1 会导致很多人出局
-
我在您发布的代码中没有看到
while(enumerator.hasNext()){。 -
请不要在收到答案后破坏问题。 Stack Overflow 上不允许这样做
标签: c++ pointers linked-list enumeration friend