我从“三法则”开始阅读了一些内容,这让我在编写 C++ 时接触到了内存管理,而这对来自 Java 背景的人来说是一个挑战。
我只是开始编写一些玩具程序,只是想构建一个基本的链表。
我有我的节点:
class Node
{
public:
std::string des;
int val;
Node *nxt;
Node();
Node(std::string d, int v) : des(d), val(v);
~Node();
private:
}
还有我的链接列表:
class LinkedList
{
public:
Node *hd;
Node *tl;
LinkedList() : hd=nullptr, tl=nullptr;
void Append(const Node &nod)
{
hd=nod;
}
~LinkedList();
private:
}
我想根据我迄今为止所学到的知识来编写这样的代码。
int main(void)
{
std::cout << "Create some objects on the stack." << std::endl;
LinkedList m_ls();
Node m_nod1("first node", 30);
Node m_nod1("second node", 36);
Node m_nod1("third node", 42);
m_ls.Append(m_nod1);
m_ls.Append(m_nod2);
m_ls.Append(m_nod3);
}
我收到了明显的编译器警告,因为我分配了 this->hd=nod 但对我来说如何正确编写它并不明显。类型和复制构造函数之间的转换可以解决这个问题吗?感谢您的帮助。
编写这段代码的正确方法是根本不让用户传入
Node
对象。他们应该传入他们想要的数据,让 LinkedList
类根据需要在内部处理 Node
。
例如:
class Node
{
public:
std::string des;
int val;
Node *nxt = nullptr;
Node(std::string d, int v) : des(d), val(v) {}
};
class LinkedList
{
public:
LinkedList() = default;
LinkedList(const LinkedList&) = delete;
LinkedList(LinkedList&&) = delete;
LinkedList& operator=(const LinkedList&) = delete;
LinkedList& operator=(LinkedList&&) = delete;
~LinkedList()
{
Node *nd = hd, *nxt;
while (nd)
{
nxt = nd->nxt;
delete nd;
nd = nxt;
}
}
void Append(std::string des, int val)
{
Node *n = new Node(des, val);
if (!hd) hd = n;
if (tl) tl->next = n;
tl = n;
}
private:
Node *hd = nullptr;
Node *tl = nullptr;
};
int main()
{
std::cout << "Create some objects in the list." << std::endl;
LinkedList m_ls;
m_ls.Append("first node", 30);
m_ls.Append("second node", 36);
m_ls.Append("third node", 42);
}