4

所以,我认为从原始指针转换为唯一指针一点也不难。然而,当我试图为自己做一个时,我遇到了很多我什至不知道的问题。下面的这个例子将更多地解释我的意思。我从 Visual Studio 得到了很多错误,我不知道如何修复它。谁能告诉我我做错了什么?谢谢

Contact.h

#pragma once
#include<iostream>
#include<string>
#include<memory>

class Contact
{
    friend std::ostream& operator<<(std::ostream& os, const Contact& c);
    friend class ContactList;

public:
    Contact(std::string name = "none");

private:
    std::string name;
    //Contact* next;    
    std::unique_ptr<Contact> next;
};

联系人.cpp

#include"Contact.h"

using namespace std;

Contact::Contact(string n):name(n), next(new Contact())
{
}

ostream& operator<<(ostream& os, const Contact& c)
{
    return os << "Name: " << c.name;
}

联系人列表.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   2   error LNK1120: 1 unresolved externals   E:\Fall 2013\CPSC 131\Practice\Practice\Debug\Practice.exe  1

错误 1 ​​错误 LNK2019:未解析的外部符号“public: __thiscall ContactList::~ContactList(void)” (??1ContactList@@QAE@XZ) 在函数“public: void * __thiscall ContactList::`scalar Delete destructor'(unsigned int)" (??_GContactList@@QAEPAXI@Z) E:\Fall 2013\CPSC 131\Practice\Practice\Practice\ContactListApp.obj

4

1 回答 1

3

unique_ptr有空的构造函数和 nullptr 构造函数,它什么也没说 0。

constexpr unique_ptr();
constexpr unique_ptr( nullptr_t );
explicit unique_ptr( pointer p );
unique_ptr( pointer p, /* see below */ d1 );
unique_ptr( pointer p, /* see below */ d2 );
unique_ptr( unique_ptr&& u );
template< class U, class E >
unique_ptr( unique_ptr<U, E>&& u );
template< class U >
unique_ptr( auto_ptr<U>&& u );

此外,您将希望使用void swap(unique_ptr& other)在 unique_ptrs 之间交换指针,而不像使用operator=. 记住所有这些,再试一次,您应该仔细查看cppreference.com unique_ptr页面以了解它是如何工作的。

如果我是你,我会使用链接列表的第二个注意事项,我会使用原始指针。

于 2013-10-07T07:26:37.763 回答