linkedlist.h
#ifndef LINKEDLIST_H_
#define LINKEDLIST_H_
#include <iostream>
template <typename T>
class list{
public:
list();
class node;
typedef T value_type;
typedef T& reference;
typedef node node_type;
typedef node_type* node_pointer;
list& push_back(value_type);
value_type pop_front();
node_pointer begin() const;
private:
node_pointer head, tail;
};
template <typename T>
class list<T>::node{
public:
node(value_type value = 0);
void setData(value_type);
value_type getData() const;
void setNext(node_pointer);
node_pointer getNext() const;
private:
value_type data;
node_pointer ptr_next;
};
template <typename T>
inline list<T>::node::node(value_type value) : data(value), ptr_next(nullptr){
}
template <typename T>
void list<T>::node::setData(value_type value){
this->data = value;
}
template <typename T>
typename list<T>::value_type list<T>::node::getData() const{
return this->data;
}
template <typename T>
void list<T>::node::setNext(node_pointer ptr){
this->ptr_next = ptr;
}
template <typename T>
typename list<T>::node_pointer list<T>::node::getNext() const{
return this->ptr_next;
}
template <typename T>
list<T>::list() : head(nullptr), tail(nullptr){
}
template <typename T>
list<T>& list<T>::push_back(value_type value){
node_pointer item = new node_type(value);
if(this->tail) this->tail->setNext(item);
this->tail = item;
if(!this->head) this->head = this->tail;
return *this;
}
template <typename T>
typename list<T>::value_type list<T>::pop_front(){
if(this->head){
node_pointer item = this->head;
value_type value = this->head->getData();
this->head = this->head->getNext();
delete item;
return value;
}
return 0;
}
template <typename T>
typename list<T>::node_pointer list<T>::begin() const{
return this->head;
}
template <typename T>
std::ostream & operator<<(std::ostream &stream, list<T> &obj){
typename list<T>::node_pointer ptr = obj.begin();
while(ptr->getNext() != nullptr){
stream << ptr->getData() << " ";
ptr->setNext(ptr->getNext());
}
return stream;
}
#endif /* LINKEDLIST_H_ */
的main.cpp
#include <iostream>
#include "LinkedList.h"
using std::cout;
using std::endl;
int main (int argc, char ** argv){
list<int> mylist;
mylist.push_back(5).push_back(1);
cout << mylist;
return 0;
}
我只是想创建一个重载operator<<
的打印函数。无论我做了什么,我找不到解决方案。这个重载运算符有什么问题&lt;&lt;功能?如果程序抛出错误,我怎么能清理垃圾。析构函数应该如何?
答案 0 :(得分:0)
template <typename T>
std::ostream & operator<<(std::ostream &stream, list<T> &obj){
typename list<T>::node_pointer ptr = obj.begin();
while(ptr != nullptr){
stream << ptr->getData() << " ";
ptr = ptr->getNext();
}
return stream;
}
我意识到我在打印功能期间犯了一个逻辑错误。但我仍然想知道如何收集垃圾?