[英]How can a template class be an attribute of another template class of the same type T in c++?
I have a template class Tripla (node for a list structure) and another template class Lista . 我有一个模板类Tripla (列表结构的节点)和另一个模板类Lista 。 I want to make them generic so they can reused in the future, however I'm not sure how to set the data type to the Tripla objects from the class 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;
}
} }
Some compilation errors include not being able to convert Tripla*
to Tripla<T>*
and "error C2955: 'Tripla' : use of class template requires template argument list". 某些编译错误包括无法将
Tripla*
转换为Tripla<T>*
和“错误C2955:'Tripla':使用类模板需要模板参数列表”。
I am having problems understanding how to set the same data type to both. 我在理解如何为两者设置相同的数据类型时遇到问题。 For example, from main.cpp, I want to have something like
例如,在main.cpp中,我想要类似
Lista list<int>.menu()
and that will automatically make Tripla *primer and *ultimo work with int. 这将自动使Tripla * primer和* ultimo与int一起使用。
You are missing some template arguments in some places. 您在某些地方缺少一些模板参数。 First of all:
首先:
Tripla *anterior;
Tripla *siguente;
should be: 应该:
Tripla<T> *anterior;
Tripla<T> *siguente;
And then: 接着:
primer = new Tripla;
should be: 应该:
primer = new Tripla<T>;
Also notice that there already exist a linked list (and even doubly linked list) implementation in the standard library: std::forward_list
for singly linked lists and std::list
for doubly linked list. 还要注意,标准库中已经存在一个链表(甚至是双链表)实现:
std::forward_list
用于单链表, std::list
用于双链表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.