所以,我认为从原始指针转换为唯一指针一点也不难。然而,当我试图为自己做一个时,我遇到了很多我什至不知道的问题。下面的这个例子将更多地解释我的意思。我从 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