[英]Having problems using a template on a struct
我是编程和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 ++,而是读一本好书 。
template <typename TElement>
struct list{
这将声明一个名为list
的结构模板,该结构模板具有一个模板参数TElement
,该参数用作实例化模板所用类型的别名(仅在模板主体内)。
如果实例化list<int>
则TElement
将引用int
。 如果实例化list<char>
则TElement
将引用char
。 等等
因此,实例化模板所用的类型将替换模板定义中的TElement
。
您尝试时遇到的错误:
// if I try list<TElement> => list is not a template
template <typename TElement>
struct list<TElement> {
是因为这是无效的语法,错误是告诉您list
不是模板,因为在您编写list<TElement>
您还没有完成声明list
,因此编译器不知道它是什么,而您如果未定义列表模板,则无法包含某些内容的列表。
template <typename TElement>
struct list{
TElement data;
struct list *next;
}node_type;
这尝试声明一个类型为list
的对象,类似于以下语法:
struct A {
int i;
} a; // the variable 'a' is an object of type 'A'
但在您的情况下, list
不是类型,而是模板。 list<int>
是一种类型,但是list
本身不是有效的类型,它只是当您“填空”时可以从中创建类型的模板,即提供一种类型来代替参数TElement
看起来您甚至都没有试图声明变量,只是盲目地猜测语法。
// also tried node_type<TElement>, other incomprehensible errors
那也无济于事, node_type<TElement>
是胡说八道,如果您想声明一个变量,它需要一个类型,例如list<int>
。 参数TElement
需要替换为类型,它本身不是类型。 停止尝试将语法的随机位组合在一起,希望它能起作用。 您可以先阅读http://www.parashift.com/c++-faq/templates.html
在最后一行:
node_type *ptr[max], *root[max], *temp[max];
node_type
不是类型,因此无法正常工作。 同样,您应该避免养成在一行上声明多个变量的坏习惯。 编写起来更加清晰:
int* p1;
int* p2;
代替
int *p1, *p2;
另外,您确定要指针数组吗? 由于您显然不知道自己在做什么,因此使用适合您的工作的标准容器类型会更明智。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.