代码之家  ›  专栏  ›  技术社区  ›  Nick

用指针和常量方法初始化

  •  1
  • Nick  · 技术社区  · 7 年前

    假设我们有T的链表类。 (我不知道代码是否有效)

    template <typename T>
    struct List{
    
       struct Node{
          T data;
          Node *next;
       };
    
       // add, remove etc...
    
       Node *locate(const T &a) const{
          for(Node *node = head; node; node = node->next)
             if (node->data == a)
                return node;
    
          return nullptr;
       }
    
    private;
       Node *head;
    };
    

    如果你检查方法 locate ,它基本上可以伤害和破坏链接列表,甚至方法标记为 const .

    我只是注意到了一些其他的事情。由于节点不是常量,因此也可以更改节点::数据。

    如果这是程序员的错误,是否有C++的方法可以避免呢?

    我知道这个方法可以写成这样。

        const Node *locateConst(const T &a) const{
          for(const Node *node = head; node; node = node->next)
             if (node->data == a)
                return node;
    
          return nullptr;
       }
    
    3 回复  |  直到 7 年前
        1
  •  0
  •   user9876    7 年前

    const List *const_list const_list->head const_list->head->next const_list->head->data

    const List

        2
  •  1
  •   Red.Wave P.W    7 年前
        3
  •  0
  •   catnip    7 年前

    head *head

    推荐文章