链接堆栈中的唯一指针

时间:2013-10-07 23:23:47

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

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

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 2013\cpsc 131\hw4\hw4\hw4\compactstack.h    23

1 个答案:

答案 0 :(得分:1)

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

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

This可以帮到你。