如何使用来自友元函数的嵌套类?

How can I use a nested class from a friend function?

本文关键字:嵌套 函数 友元 何使用      更新时间:2023-10-16

就像我得到一个解决方案一样,我有另一个问题。看,我的模板链表中有一个朋友语句,我需要把它作为朋友才能访问我的私有嵌套节点结构。

template <typename T>
class LL;
template <typename T>
std::ofstream& operator<< (std::ofstream& output, LL<T>& obj);
template <typename T>
class LL
{
struct Node
{
T mData;
Node *mNext;
Node();
Node(T data);
};
private:
Node *mHead, *mTail;
int mCount;
public:
LL();
~LL();
bool insert(T data);
bool isExist(T data);
bool remove(T data);
void showLinkedList();
void clear();
int getCount() const;
bool isEmpty();
friend std::ofstream& operator<< <>(std::ofstream& output, LL& obj);
};
template <typename T>
std::ofstream& operator<<(std::ofstream& output, LL<T>& obj)
{
Node* tmp;
if (obj.mHead != NULL)
{
tmp = obj.mHead;
while (tmp != NULL)
{
output << tmp->mData << std::endl;
tmp = tmp->mNext;
}
}
return output;
}

请注意,我需要 friend 运算符<<函数定义中的"tmp->mData"部分来处理模板。不幸的是,我现在得到的唯一错误是在友元函数定义中。它不理解"节点",尽管它是一个朋友函数。我很困惑。希望有人能帮助我。

作为朋友,以及一般的访问控制,永远不会影响名称查找。 (这有时是没有帮助的,但正交性很容易推理,并保证更改成员的访问权限不会改变程序的含义(某些 SFINAE 情况除外),只是可能使其无法编译。 因此,就像私密不会阻止找到名字一样,成为朋友也无助于找到它。 用

typename LL<T>::Node *tmp;