链接堆栈中的唯一指针



所以,从链表开始,我现在必须构建一个链接堆栈,我认为它与它非常相似。但是,我收到一个访问错误,说无法访问我不理解的私人成员,因为我根本没有尝试访问任何私人成员......

LinkNode.h

#include <iostream>
#include <memory>
using namespace std;
template <class T>
class LinkedNode 
{
    public:
        LinkedNode(T newElement, unique_ptr<LinkedNode<T>> newNext):element(newElement), next(newNext ? new LinkedNode<T>newNext : nullptr)
        {
        }
        T GetElement() {return element;}
        void SetElement(T x) {element = x;}
        unique_ptr<LinkedNode<T>> newNext() {return next;}
        void SetNext(unique_ptr<LinkedNode<T>> newNext) {next = newNext;}
    private:
        T element;
        unique_ptr<LinkedNode<T>> next;
};

CompactStack.h

#pragma once
#include"LinkedNode.h"
using namespace std;
template <class T>
class CompactStack 
{
    public:
        CompactStack() {}
        bool IsEmpty() const { return head == 0; }
        T Peek() 
        {
            assert(!IsEmpty());
            return head-> GetElement();
        }
        void Push(T x) 
        {
            unique_ptr<LinkedNode<T>> newhead(new LinkedNode<T>(x, head));
            head.swap(newhead);
        }
        void Pop() 
        {
            assert(!IsEmpty());
            unique_ptr<LinkedNode<T>> oldhead = head;
            head = head->next();
        }
        void Clear() 
        {
            while (!IsEmpty())
            Pop();
        }
    private:
        unique_ptr<LinkedNode<T>> head;
};

这是我从编译器那里得到的错误

Error   1   error C2248: 'std::unique_ptr<_Ty>::unique_ptr' : cannot access private member declared in class 'std::unique_ptr<_Ty>' e:fall 2013cpsc 131hw4hw4hw4compactstack.h    23

即使你不直接访问unique_ptrLinkedNode的默认复制构造函数也在访问它。现在,unique_ptr可以移动,但不能复制。

您必须定义自己的复制 ctor,以便从指向的内容重新创建unique_ptr,而不是通过复制旧内容直接构造一个。

这应该对您有所帮助。

最新更新