c++ - 链表中的唯一指针

标签 c++ list pointers linked-list unique

我试图通过使用唯一指针创建一个链表。但是,由于一些我不知道如何修复的奇怪错误,我的程序无法编译。谁能帮我解决这个问题?谢谢。

联系人列表.h

#pragma once
#include"Contact.h"
#include<memory>

using namespace std;

class ContactList
{
public:
    ContactList();
    ~ContactList();
    void addToHead(const std::string&);
    void PrintList();

private:
    //Contact* head;
    unique_ptr<Contact> head;
    int size;
};

联系人列表.cpp

#include"ContactList.h"
#include<memory>

using namespace std;

ContactList::ContactList(): head(new Contact()), size(0)
{
}

void ContactList::addToHead(const string& name)
{
    //Contact* newOne = new Contact(name);
    unique_ptr<Contact> newOne(new Contact(name));

    if(head == 0)
    {
        head.swap(newOne);
        //head = move(newOne);
    }
    else
    {
        newOne->next.swap(head);
        head.swap(newOne);
        //newOne->next = move(head);
        //head = move(newOne);
    }
    size++;
}

void ContactList::PrintList()
{
    //Contact* tp = head;
    unique_ptr<Contact> tp(new Contact());
    tp.swap(head);
    //tp = move(head);

    while(tp != 0)
    {
        cout << *tp << endl;
        tp.swap(tp->next);
        //tp = move(tp->next);
    }
}

这些是我遇到的错误:

Error   1   error LNK2019: unresolved external symbol "public: __thiscall ContactList::~ContactList(void)" (??1ContactList@@QAE@XZ) referenced in function "public: void * __thiscall ContactList::`scalar deleting destructor'(unsigned int)" (??_GContactList@@QAEPAXI@Z) E:\Fall 2013\CPSC 131\Practice\Practice\Practice\ContactListApp.obj
Error   2   error LNK1120: 1 unresolved externals   E:\Fall 2013\CPSC 131\Practice\Practice\Debug\Practice.exe  1

最佳答案

您的 ContactList 析构函数没有实现。

添加到ContactList.cpp

ContactList::~ContactList()
{
}

或者(因为析构函数无论如何都是微不足道的),只需从类定义中删除显式析构函数:

class ContactList
{
public:
    ContactList();
    // no explicit destructor required
    void addToHead(const std::string&);
    void PrintList();

private:
    unique_ptr<Contact> head;
    int size;
};

关于c++ - 链表中的唯一指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19220333/

相关文章:

c++ - Fortran调用C++指针函数

c++ - 使用标准库基于一个数组对两个数组进行排序(避免复制步骤)

c++ - 如何使用具有默认值的参数制作函数原型(prototype)?

jquery - 在动态生成的列表中选择列表元素

c++ - 为什么指针用于 std::string.find?

java - 尝试在java中返回HashMap值时出现空指针异常

c++ - 如何配置 Emacs 以突出显示违反详细代码样式的 C++?

c++ - 使用引用而不是指针可以解决 C++ 中的内存泄漏问题吗?

python - 为什么附加到一个列表也会附加到我的列表中的所有其他列表?

python - python中list的append函数的使用