使用泛型创建链表
我已经阅读了如何创建指向普通类的指针并在类定义中使用它:
type
PExample = ^TExample;
TExample = class
data: Integer;
next: PExample;
end;
但是如何使用模板化参数来做到这一点?这不会在第二行编译时出现错误未声明的标识符:'TExample'
:
type
PExample = ^TExample;
TExample<T> = class
data: T;
next: PExample;
end;
将其更改为
PExample = ^TExample<T>;
并不能修复它。
I have read how to make a pointer to a normal class and use it inside the class difinition:
type
PExample = ^TExample;
TExample = class
data: Integer;
next: PExample;
end;
but how do you do it with templatized parameters? This does not compile with the error Undeclared identifier: 'TExample'
on the second line:
type
PExample = ^TExample;
TExample<T> = class
data: T;
next: PExample;
end;
Changing it to
PExample = ^TExample<T>;
does not fix it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
由于您使用的是类,因此不需要使用 PExample。类已经是引用类型。
这应该可以工作,而不需要声明任何指针类型。仅当您使用记录(值类型)时才需要指针类型。
编辑:
令我惊讶的是,我刚刚注意到这在 Delphi XE 中编译和工作:
它仍然没有解决定义一般通用指针类型的问题,因为这:
不起作用。
As you are using a class, you don't need to use a PExample. Classes are already reference types.
This should work without the need to declare any pointer types. Pointer types are only required if you work with records (which are value types).
EDIT:
To my surprise I just noticed that this compiles and works in Delphi XE:
It does still not solve the problem of defining a general generic pointer type, because this:
does not work.
其他答案告诉您如何构建类的通用链接列表。如果您需要构建通用的记录链接列表,目前无法这样做:
无法编译。
也不:
我认为其原因是单遍编译器不支持方法的前向声明。实际上,这对于运算符重载来说比对于泛型来说更实际,因为类可以用于泛型链表。
The other answers tell you how to build a generic linked list of classes. If you ever need to build a generic linked list of records, you cannot do so at present:
does not compile.
Nor does:
I believe that the reason for this is that the single-pass compiler does not support forward declarations of methods. This is actually more of a practical problem for operator overloading than for generics because classes can be used for generic linked lists.
是否有必要使用指向类的指针?对“下一个”字段使用类引用应该可行,如下所示:
“下一个”字段仍然可以是 NIL,或者可以分配另一个 TExample 实例。这似乎否定了使用传统 ^ 指针的需要(尽管您可能会争辩说对类的引用也是一个指针,只是语法不同)。
Is it necessary to use a pointer to a class? Using a class reference for your "next" field should work, like this:
The "next" field can still be NIL or can be assigned another TExample instance. This seems to negate the need of using a traditional ^ pointer (although you could argue that a reference to a class is also a pointer, just with different syntax).