使用私钥成员为 class 重载 ostream << 运算符

Overloading ostream << operator for a class with private key member

我正在尝试为 class List

重载 ostream << 运算符
class Node
{
public:
    int data;
    Node *next;
};
class List
{
private:
    Node *head;
public:
    List() : head(NULL) {}
    void insert(int d, int index){ ... }
 ...}

据我所知(重载ostream函数)必须写在class之外。所以,我这样做了:

ostream &operator<<(ostream &out, List L)
{
    Node *currNode = L.head;
    while (currNode != NULL)
    {
        out << currNode->data << " ";
        currNode = currNode->next;
    }
    return out;
}

当然,这行不通,因为成员 Node headprivate。 这种情况除了把Node *head转成public还有什么办法呢?

您可以通过在 class' 定义中为重载的 operator<< 添加 友元声明 来解决此问题,如下所示:

class List
{
   //add friend declaration
   friend std::ostream& operator<<(std::ostream &out, List L);
   
   //other member here
};

在 class 内声明函数签名并将其标记为 friend,然后根据需要在 class 外定义它。