Reputation: 341
I am trying to overload output operator.
Program compiles, but instead of output (list of nodes) it prints some address.
Could you explain me where I made mistake?
I am sure that displayList function is correct. If you see also something incorrect, please get me know.
EDIT: if I dereference myList, I get error: undefined reference to `operator<<(std::ostream&, SingleLinkedList const&)' Something is wrong with const?
full, executable code - https://codepad.remoteinterview.io/DPAXORFXKM
output:
Constructor called...
Display function:
10 --> 20 --> 30 -->
Display - overloaded operator:
0x9152a10
Destructor called...
template <typename T>
class SingleLinkedList{
protected:
struct Node{
T data;
Node * next;
Node() : next(nullptr) {}
Node(const int num) : data(num), next(nullptr) {}
};
private:
Node * head;
Node * tail;
public:
SingleLinkedList();
~SingleLinkedList();
void insert(T const& value);
void displayList(std::ostream& stream = std::cout);
friend std::ostream& operator<<(std::ostream& os, const SingleLinkedList& list);
};
template <typename T>
void SingleLinkedList<T>::displayList(std::ostream& stream){
Node * temp = nullptr;
temp = head;
while(temp!=nullptr){
stream << temp->data << " --> ";
temp = temp->next;
}
stream << std::endl;
}
template <typename T>
std::ostream& operator<<(std::ostream& os, const SingleLinkedList<T>& list){
list.displayList(os);
return os;
}
int main(){
SingleLinkedList<int> * myList = new SingleLinkedList<int>();
myList->insert(10);
myList->insert(20);
myList->insert(30);
std::cout << "Display function:" << std::endl;
myList->displayList();
std::cout << "Display - overloaded operator:" << std::endl;
std::cout << myList << std::endl;
delete myList;
return 0;
}
Upvotes: 1
Views: 72
Reputation: 3707
Many errors:
first, remove friend std::ostream& operator<<(std::ostream& os, const SingleLinkedList& list);
, it's not necessary
second, change displayList
to be const
(indeed, this function doesn't modify list and it doesn't have to - in a general way, always mark function which haven't to modify instance as const
- const
functions can be called for const
instance, as you have inside your operator<<
):
void displayList(std::ostream& stream = std::cout) const;
and
template <typename T>
void SingleLinkedList<T>::displayList(std::ostream& stream) const{
and finally, display list instead of pointer to list by dereferencing it :
std::cout << *myList << std::endl;
Upvotes: 3
Reputation: 110
You are handing myList to std::cout. This variable is a pointer to the list.
To print out the list itself you have to dereference the pointer:
std::cout << "Display - overloaded operator:" << std::endl;
std::cout << *myList << std::endl;
Upvotes: 4