C ++转换问题

时间:2013-12-26 12:26:54

标签: c++ type-conversion const

我有一个semestral工作(自己的双链表),我们的老师想要这个类DoubleList的定义:

template <typename T>   //just part of all methods
class DoubleList { 
public: 

    DoubleList(void);   //We HAVE TO follow this definitions 

    void AddFirst(const T &);     //const!
    T &AccessActual(void); 
    T RemoveFirst(void);
}

我的问题是,如何定义节点? AddFirst有const参数,其他方法没有。必须在构造函数中设置数据,然后才能更改它们。这项任务是如此有限还是其他方式来完成任务?

这是我的实际Node

template <class U>
        class Node{
            Node<U> * next;
            Node<U> * previous;
            const U * data;
        public:
            Node(const U *data){   //
                next = NULL;
                previous = NULL;
                this->data = data;
            }
            void SetNext(Node<U> *next) { 
                this->next = next; 
            }
            Node<U> *GetNext(){ return next; }
            void SetPrevious(Node<U> *previous) { 
                this->previous = previous; 
            }
            Node<U> *GetPrevious(){ return previous; }
            const U *GetData() { return data; }
        };

2 个答案:

答案 0 :(得分:0)

在容器中,通常最好拥有数据副本,然后将const U * data;更改为U data;

如果具有此签名Node(const U& data),则Node构造函数将更易于使用。没有指针。

GetData也必须改变。返回参考。 U& GetData()

保存数据项的地址是危险的。如果列表的用户想要该功能,他可以使用存储指针的列表(例如,U = int *)

答案 1 :(得分:0)

你的节点类看起来很好,虽然我会继续使用模板参数T而不是U,现在它很混乱。

你的AddFirst()方法应该只创建一个新节点,并为新节点分配正确的下一个指针,并将正确的prev指针分配给“旧”第一个节点并调整实际对象?那指的是什么?

您的节点接口与此节点的接口不同,它返回引用而不是指针。我觉得很奇怪,AccessActual总是可以返回一个对象,而当列表为空时,这可能是一个nullptr ??

示例实现:

void AddFirst(const T &)
{
  Node<T>* newNode = new Node<T>(T);
  Node<T>* current = &AccessActual(); // how can there be an actual when the list can be empty or is that impossible?

  {
     while( current.GetPrev() != nullptr )
     {
        current = *current.GetPrev();
     }
     current.SetPrev(newnode);
     newnode->SetNext(current);

  }

}
相关问题