2017-09-29 39 views
0

我真的很新使用链接列表。我试图超载与decleration一个双向链表中的ostream opperator:链接列表ostream超载奇怪值

template <class T> 
class DynamicList; 

template <class T> 

template <class T> 
class DynamicList 
{ 
private: 

Node<T> *head; 

public: 
class Node 
{ 
public: 

    T* value; 
    Node<T> *next; 
    Node<T> *prev; 

    Node(T val) 
    { 
     next = nullptr; 
     prev = nullptr; 
     value = &val; 
    } 

}; 
DynamicList(); 
~DynamicList(); 


void operator+=(const T); 


friend std::ostream & operator<< <>(std::ostream &, const DynamicList<T> &); 
}; 

和功能defenition:

template <class T> 
ostream& operator << (ostream & out , const DynamicList<T> & rhs) 
{ 
    Node<T>* nodePtr = rhs.head; 
    Node<T>* nptr = nodePtr->next; 
    while(nodePtr != NULL) 
{ 
    cout<<*(nodePtr->value)<<" "; 
    nodePtr = nodePtr->next; 
} 
out<<endl; 
return out; 
} 

template <class T> 
void DynamicList<T>:: operator +=(const T val) 
{ 
Node<T>* nodePtr = nullptr; 
T vall = val; 
Node<T>* newNode = new Node<T>(vall); 
if(!head) 
{ 
    head = newNode; 
} 
else 
{ 
    nodePtr = head; 
    while((nodePtr->next)) 
    { 
     nodePtr = nodePtr->next; 
    } 
    nodePtr->next = newNode; 
    newNode->prev = nodePtr; 
} 

每次我打电话opperator它给例如一个奇怪的输出使用:

for(int i = 1; i <= 3; i++) 
{ 
    list += i; 
} 
cout<<list; 

它将给像135727363 135727383 135727383的输出,我只是想知道我做错了,可能我怎么能解决这个问题

回答

-1

你的问题是在这里:

T* value; 

您存储的值的地址。
问题是您正在存储已超出范围的变量的地址。

T vall = val; 
Node<T>* newNode = new Node<T>(vall); 

可变vall是本地函数operator +=,这意味着它的存在后它不再存在(并且可以包含任何东西)。

修复更改节点以存储值。

class Node 
{ 
public: 

    T  value; // Notice no star here. 
    Node<T> *next; 
    Node<T> *prev; 

    Node(T const& val)  // Add `const&` here to avoid a copy. 
    { 
     next = nullptr; 
     prev = nullptr; 
     value = val;  // Notice no and `&` here 
    } 

};