我是编程和 C++ 的初学者。我以前使用过模板,但使用方式非常有限,我不知道自己做错了什么:
template <typename TElement>
struct list{ // if I try list<TElement> => list is not a template
TElement data;
struct list *next;
} node_type; // also tried node_type<TElement>, other incomprehensible errors
node_type *ptr[max], *root[max], *temp[max];
我发现错误有点难以理解:“node_type does not name a type”
我做错了什么?
我打算做什么:
我想要一个类型列表(这样我就可以在几个完全不同的抽象数据类型 - ADT 上使用它),所以我想以这样的方式结束:
Activities list *ptr[max], *root[max], *temp[max]
如果这有意义(其中 Activities
是一个类,但可以是任何其他类)。
最佳答案
试试这个:
template <typename TElement>
struct node{
TElement data;
node* next;
};
node<int>* ptr[max], *root[max], *temp[max];
另外一个建议:避免使用标准 C++ 库中的类型命名您的自定义类型(例如 list
、vector
、queue
...都在命名空间 std
中)。这很困惑,并可能导致名称冲突(除非您将它放在您自己的命名空间中,您需要在放置 using namespace std;
的任何地方显式使用它)。
关于c++ - 在结构上使用模板时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10802480/