Home > Net >  Overloading and LinkedList
Overloading and LinkedList

Time:03-12

I was trying to overload cout operator to print a class.

The class consists of an integer value and a pointer. So I was hoping to print an integer value and a memory address, but I got an error. I got confused since the class itself already has a pointer and couldn't figure out the problem.

The compiler gives "expected primary-expression before '.' token" error for the overloading part of the code.

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

}

CodePudding user response:

First, generally we need to add a friend declaration for the overloaded operator<< so that the be-friended function can access the private fields of the class type as shown below. But since both the data members of your class type are public you can skip the friend declaration.

Second, Node.value should be replaced by head.value as shown below.

Third, cout << head should be replaced by cout << *head as shown below:

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 

}

Also, don't forget to use delete(when/where needed) so that you don't have memory leaks.

  • Related