【问题标题】:Unique pointer in Linked List链表中的唯一指针
【发布时间】:2013-10-07 08:41:02
【问题描述】:

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

联系人列表.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

【问题讨论】:

  • 您的代码确实编译。它没有链接。这些错误也不是那么奇怪(模板编译错误很奇怪)。学习阅读编译器和链接器的输出是学习 C++ 和编写代码的一部分。
  • @Johnsyweb:谢谢,我想学习如何阅读编译器需要时间和大量练习

标签: c++ list pointers linked-list unique


【解决方案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;
};

【讨论】:

  • 是的。使用智能指针的好处之一是我们需要编写的析构函数要少得多。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多