所以我准备把我的电脑扔出窗外,现在我认为我应该在销毁昂贵的设备之前寻求帮助。
我的程序有一个自动填写的列表(我手动输入项目),它只是输出它。然后,我有另一个代码块,它是使用赋值运算符再次输出它,然后是带有复制构造函数的第三个副本。
赋值运算符使程序崩溃,但如果我将其注释掉以使其到达复制构造函数,则列表为空。
任何说“TODO”的东西你都可以忽略,我会在以后修复它。
这是所有动作发生的地方:
列表.cpp
(这不是我的主要功能,那里没有错)
List::List() : m_pFront(0), m_pBack(0), _pData(0)
{}
List::~List()
{
Clear();
}
List::List(const char* p)
{
if(!p)
{
_pData = 0;
return;
}
if(strlen(p) == 0)
{
_pData = 0;
return;
}
_pData = new char[strlen(p) + 1];
strcpy(_pData, p);
}
void List::Clear()
{
//delete
if(!m_pFront)
{
return;
}
delete m_pFront;
Node* p = m_pBack;
//Walking the list
while(p)
{
//Get a pointer to the next in the list
Node* pTemp = p -> m_pNext;
delete p;
//Move p along the list
p = pTemp;
}
m_pFront = 0;
m_pBack = 0;
}
void List::PushFront(std::string data)
{
//create a new node
Node* p = new Node(data);
//Empty list
if(!m_pFront)
{
m_pFront = p;
m_pBack = p;
}
else //Not empty list
{
p -> m_pNext = m_pFront;
m_pFront -> m_pPrev = p;
m_pFront = p;
}
}
void List::PushBack(std::string data)
{
Node* p = new Node(data);
if(!m_pBack)
{
m_pFront = p;
m_pBack = p;
}
else
{
p -> m_pPrev = m_pBack;
m_pBack -> m_pNext = p;
m_pBack = p;
}
}
void List::PopFront()
{
if(m_pFront == 0)
{
//TODO: we need to handle this problem
return;
}
if(m_pBack == m_pFront)
{
Clear();
return;
}
Node* p = m_pFront;
m_pFront = m_pFront -> m_pNext;
p -> m_pNext = 0;
m_pFront -> m_pPrev = 0;
delete p;
}
void List::PopBack()
{
if(m_pBack == 0)
{
//TODO: we need to handle this problem
return;
}
if(m_pBack == m_pFront)
{
Clear();
return;
}
Node* p = m_pBack;
m_pBack = m_pBack -> m_pPrev;
p -> m_pPrev = 0;
m_pBack -> m_pNext = 0;
delete p;
}
ostream& List::OutPut(ostream& os)
{
if(Empty() == true)
{
os << "<empty>";
}
else
{
m_pFront -> OutputNode(os);
}
return os;
}
std::string& List::Back() const
{
if(m_pBack == 0)
{
//TODO: we need to handle this problem
}
return m_pBack -> GetData();
}
std::string& List::Front() const
{
if(m_pFront == 0)
{
//TODO: we need to handle this problem
}
return m_pFront -> GetData();
}
//Copy Constructor
List::List(const List& str)
{
if(Empty() == true)
{
_pData = 0;
return;
}
_pData = new char[strlen(str._pData) + 1];
strcpy(_pData, str._pData);
}
//Deep copy
List& List::operator=(const List& str)
{
if(&str == this)
{
return *this;
}
delete [] _pData;
_pData = new char[strlen(str._pData) + 1];
strcpy(_pData, str._pData);
return *this;
}
编辑:这是创建 List 类的地方,如果这也需要查看的话
列表.h
class List
{
public:
List();
List(const char* p);
//Copy constructor
List(const List& str);
//Deep Copy
List& operator=(const List& str);
~List();
void Clear();
//Adds to the front
void PushFront(std::string data);
//adds to the back
void PushBack(std::string data);
//removes from the front
void PopFront();
//removes from the back
void PopBack();
//gets the back value
std::string& Back() const;
//gets the from value
std::string& Front() const;
bool Empty() const {return m_pFront == 0;}
ostream& OutPut(ostream& os);
private:
Node* m_pFront;
Node* m_pBack;
char* _pData;
};