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.
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;
}
Aucun commentaire:
Enregistrer un commentaire