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

有人能解释一下C++代码是我的一部分吗?

c++
  •  0
  • MHA  · 技术社区  · 5 年前

    我知道这个问题不会很具体,但我不知道这段代码在做什么:

    我有一个类的构造函数: ListNode(const T & data) : data(data), next(nullptr) {} 然后初始化为nullptr。

    template <typename T>
    const T & List<T>::operator[](unsigned index) {
      ListNode *thru = head_;
    
      while (index > 0 && thru->next != nullptr) {
        thru = thru->next;
        index--;
      }  
    
      return thru->data;
    }
    

    这是在试图定义 [] thru = thru->next; index-- 是在这个代码的上下文中完成的吗?

    0 回复  |  直到 5 年前
        1
  •  2
  •   Waqar Andrew Tomazos    5 年前

    这是否试图将[]定义为将在给定“索引”处返回“数据”的运算符?

    对。基本上这意味着你可以这样做:

    List<int> l; //suppose it has values
    int x = l[3]; //access the third element.
    

    那么thru=thru->next;想要完成什么呢?

    它试图找到 index 论点中提供的立场。你看,列表不能用索引直接访问。让我用价值观来解释:

    suppose index = 3
    
     // loop keeps running till index is not 0
      while (index > 0 && thru->next != nullptr) {
        thru = thru->next;     //move forward in list, "next" is the next item in list
        index--;               //decrease index by 1 on every iteration
      }  
    

    如果索引为3,它将递减3倍,并且 thru 将移动 向前地 按3项列出。换句话说,我们在列表中向前移动,直到索引不为0。当索引达到0时, 包含位置处的值 指数 这个值是从函数返回的。