簡體   English   中英

class 模板中的返回結構 function

[英]Return struct in class template function

我正在學習 C++ 和我前一段時間找到的一本書中的一些練習。 我的任務如下所述,我試圖找到一個解決方法來返回我為模板 function getLastNode創建的模板節點,以在列表末尾添加一個節點。 是否有可能做到這一點,目前我找不到一種方法讓我們稱之為解釋編譯器什么是 TNode 作為 class 返回值中的結構。

我可能有在此代碼中聲明節點的最佳方式。 也許,class 中的結構會使 class 模板方法實現復雜化。 你覺得還有別的策略嗎? 請告訴我

干杯!

/* Implement the data structure dynamic doubly linked list (DoublyLinkedList<T>) - list,
 * the elements of which have pointers both to the next and the previous elements. Implement 
 * the operations for adding, removing and searching for an element, as well as inserting
 * an element at a given index, retrieving an element by a given index and a method, which returns an array with the elements of the list*/

#include <iostream>

template<typename TValue>
class List{
  struct TNode{
    TValue value;
    TNode *previous;
    TNode *next;
  }Node;
  public:

    List();
    ~List();
    void addNode(TValue); 
  private:
    TNode *root;
    TNode getLastNode(TNode);
};

template<typename TValue>
List<TValue>::List():root(0) {}

template<typename TValue>
List<TValue>::~List<TValue>(){
}

template<typename TValue>
TNode List<TValue>::getLastNode(TNode node){
  if(node.next==nullptr) 
    return node;
  else
   getLastNode(node.next);
}

template<typename TValue>
void List<TValue>::addNode(TValue value){
  const TNode last = getLastNode(root);
  last.next = Node;
  last.next->value = value;
}

int main(){
  List<int> test;

  return 0;
}

要為getLastNode方法返回TNode ,我必須將auto添加到其 class 方法聲明中。

學分:@JaMiT

template<typename TValue>
auto List<TValue>::getLastNode(TNode node){
  if(node.next==nullptr)
    return node;
  else
    getLastNode(node.next);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM