【问题标题】:How can a template class be an attribute of another template class of the same type T in c++?模板类如何成为C++中相同类型T的另一个模板类的属性?
【发布时间】:2015-08-29 22:31:17
【问题描述】:

我有一个模板类 Tripla(列表结构的节点)和另一个模板类 Lista。我想让它们通用,以便将来可以重用,但是我不确定如何将数据类型设置为 Lista 类中的 Tripla 对象。

template <class T>
class Tripla
{
public:
     T element;
     Tripla *anterior;
     Tripla *siguente;
     Tripla();
     .................other functions/procedures
}; 

template <class T>
class Lista
{
private:
     Tripla<T> *primer;  // or would this simple be Tripla *primer??
     Tripla<T> *ultimo; 
     public:
     Lista();
    ~Lista();
     void insertar_principio(T);
     void menu();
     .................other functions/procedures
};

template <class T>
void Lista<T>::insertar_principio(T el)
{
if (primer == NULL)
{
    primer = new Tripla<T>; // would this be primer = new Tripla??
    ultimo = primer;
    primer->element=el;
}
else
{
    Tripla<T> *aux = primer; // would this be Tripla *aux = primer??
    primer = new Tripla;
    primer->element = el;
    aux->anterior = primer;
    primer->siguente = aux;
}

}

一些编译错误包括无法将Tripla* 转换为Tripla&lt;T&gt;* 和“错误C2955:'Tripla':使用类模板需要模板参数列表”。

我无法理解如何为两者设置相同的数据类型。 例如,从 main.cpp,我想有类似

Lista list<int>.menu()

这将自动使 Tripla *primer 和 *ultimo 与 int 一起使用。

【问题讨论】:

    标签: c++ template-classes


    【解决方案1】:

    您在某些地方缺少一些模板参数。首先:

    Tripla *anterior;
    Tripla *siguente;
    

    应该是:

    Tripla<T> *anterior;
    Tripla<T> *siguente;
    

    然后:

    primer = new Tripla;
    

    应该是:

    primer = new Tripla<T>;
    

    还要注意标准库中已经存在一个链表(甚至是双链表)实现:std::forward_list 用于单链表,std::list 用于双链表。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-26
      相关资源
      最近更新 更多