重载和链表

Overloading and LinkedList

我试图重载 cout 运算符来打印 class.

class由一个整数值和一个指针组成。所以我希望打印一个整数值和一个内存地址,但是我得到了一个错误。我很困惑,因为 class 本身已经有一个指针,无法找出问题所在。

编译器给出“'.'之前的预期主表达式”代码重载部分的令牌”错误。

#include <iostream>
using namespace std;

class Node{
public:
    int Value;
    Node* Next;

};

ostream& operator<<(ostream& a, Node& head){

    a << "Value " << Node.Value << endl;
    a << "To where " << Node.Next << endl;
    return a;
}


int main()
{
    Node* head = new Node();
    Node* second = new Node();
    Node* third = new Node();

    head -> Value = 1;
    second -> Value = 2;
    third -> Value = 3;

    head -> Next = second;
    second -> Next = third;
    third -> Next = NULL;

    cout << head;

    return 0;

}

首先,一般我们需要为重载的operator<<添加一个友元声明,这样be-friended 函数可以访问 class 类型的私有字段,如下所示。但是因为你的 class 类型的两个数据成员都是 public 可以跳过 友元声明。

其次Node.value应该换成head.value如下图。

第三个cout << head应该换成cout << *head如下图:

class Node{
public:
    int Value;
    Node* Next;
    
    //friend declaration for overloaded operator<< NOTE: Since both the data members are public you can skip this friend declaration
    friend std::ostream& operator<<(std::ostream& a, const Node& head);

};
//definition for overloaded operator<<
std::ostream& operator<<(std::ostream& a,const Node& head){

    a << "Value " << head.Value << std::endl << "To where " << head.Next;
    return a;
}
int main()
{
    Node* head = new Node();
    Node* second = new Node();
    Node* third = new Node();

    head -> Value = 1;
    second -> Value = 2;
    third -> Value = 3;

    head -> Next = second;
    second -> Next = third;
    third -> Next = NULL;

    std::cout << *head; 
    
    //don't forget to use delete to free the dynamic memory 

}

此外,不要忘记使用 delete(需要 when/where),这样就不会出现内存泄漏。