【问题标题】:Double Linked Queue with specific template具有特定模板的双链接队列
【发布时间】:2018-09-23 20:12:51
【问题描述】:

我打算做一个基于双链接双端队列的程序,其中节点具有双链接,我想做的是每个节点都是“具有名称和优先级的文档”(优先级 = 1 从头插入,prio . = 2 从后面插入)。 实际上我的代码是这样的,但我没有让所有东西都可以使用我的模板,因为我不知道如何在 Node.h 中正确声明它。

文档.h

template<class T>
class Document
{
 private:
  T name;
  T pri;

 public:
  Document(T name, T pri);
};

 template <class T> 
 Document<T>::Document(T name, T pri){
   this->name = name;
   this->pri = pri;      
}

节点.h

#include "Document.h"
template <class T> class Node{
 public:
  Node();
  Node(const T& item);
  (...other functions...)

private:
 Document<T> document;  //WHERE MY PROBLEM IS!
 Node<T>* next;
 Node<T>* previous;    
};

template <class T> 
Node<T>::Node(const T& item) {
    this->document= new Document<T>(item); //Problem with the declaration
    this->next = nullptr;
    this->previous = nullptr;
}

LinkedDeque.h

#include "Node.h"
#include "Document.h"
template <class T> class LinkedDeque {
 public:
  LinkedDeque();
  void insertFront(const T& element);
  void insertRear(const T& element);
  (... other functions ...)

private:
  Node<T>* front; //Front de la cua
  Node<T>* rear; //rear de la cua
  int num_elements;
};

template <class T>
void LinkedDeque<T>::insertFront(const T& element){

    Node<T>* aux = new Node<T>(element);

    (...rest of the function...)
}

main.cpp

LinkedDeque<Document<string>> deque;

cin >> name >> pri;
Document<string> document(name,pri);
if (pri == "1") {
  deque.insertFront(document);
}else {
  deque.insertRear(document);
}

【问题讨论】:

  • 你的问题是......?
  • 名称和优先级真的应该是同一类型吗?这听起来不对……
  • 问题是我怎样才能解决它并让它发挥作用
  • 请阅读How to Ask 并阅读如何提供minimal reproducible example。 “我的代码不起作用”不足以描述您的问题。
  • Document&lt;T&gt;(item) 不起作用的一个明显问题是,您只声明了一个需要两个参数的构造函数。

标签: c++ templates nodes deque


【解决方案1】:

我看到的第一件事是您将构造函数声明为

     Document(T name, T pri)

但您试图通过仅使用类似的项目来创建文档对象

    this->document= new Document<T>(item)

所以我建议将名称和优先级传递给您的构造函数,这样会起作用。

【讨论】:

    猜你喜欢
    • 2021-02-24
    • 2011-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-11
    相关资源
    最近更新 更多