C ++是否可以在对象之间创建私有链接?

时间:2015-05-29 19:29:20

标签: c++ linked-list

据我所知,链表只能用局外人类来实现。因为一个类不能拥有它自己类型的成员varable,并且节点列表需要该类型。问题是,如果链接打算由特定类使用。如果在外部创建链接类,则可以将其创建为独立对象。

如果链接类/结构是纯链接对象,则可以,因为它可以用于链接另一个对象类型。但是,如果我需要一个具有仅与某个对象相关的功能的链接,那么它的公共可用性将毫无意义。而且我认为将其创建为私人更好。

让我们看看this声明:

#include <unordered_map>

using namespace std;

template<class T>
class Node
{
    public:
        Node();
        Node(const T& item, Node<T>* ptrnext = NULL);
        T data;
        // access to the next node
        Node<T>* NextNode();
        // list modification methods
        void InsertAfter(Node<T>* p);
        Node<T>* DeleteAfter();
        Node<T> * GetNode(const T& item, Node<T>* nextptr = NULL);
    private:

        Node<T> * next;
        unordered_map<string, T*> nodeList;
};

unordred_map<string,T*>成员只能对某个对象有意义。因此,Node类在外面可用是没有意义的。

有可能吗?或者为链接类添加非泛型的funtionallity可能是个坏主意吗?

1 个答案:

答案 0 :(得分:0)

class A {
  A* m_pnext = nullptr;
public:
  inline A* next() { return m_pnext; }
  inline void set_next(A*ptr) { m_pnext = ptr; }
}

template <class type>
class LinkedList {
  type *m_pfirst = nullptr;
public:
  void add(type * ptr) {
    if ( nullptr == m_pfirst ) {
      m_pfirst = ptr;
    } else {
      type * n = m_pfirst, p = m_pfirst->next;
      while (nullptr != p) {
        n = p;
        p = n->next();
      }
      n->set_next(ptr);
    }
  }
};

当然,还有很大的改进空间。我会让你锻炼你的思想。