Ada 中的派生类型和子类型
有什么区别?
What are the differences?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
有什么区别?
What are the differences?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(3)
首先,术语:它是“Ada”,不是“ADA”——它是以“Ada Lovelace”命名的;它不是一个缩写词。
子类型与其基类型兼容,因此您可以将基类型的操作数与基类型的操作数混合。例如:
由于这是一个子类型,因此您可以(例如)将
1
添加到工作日以获取下一个工作日。派生类型是完全独立的类型,具有与其基类型相同的特征。不能将派生类型的操作数与基类型的操作数混合。例如,如果您使用:
那么您将无法将一个整数添加到一个工作日来获得另一个工作日。要对派生类型进行操作,您通常需要自己定义这些操作(例如,创建一个包)。同时,派生类型会“继承”其基类型的所有操作(甚至一些可能没有意义的操作),因此您仍然可以进行加法。
First of all, terminology: it's "Ada", not "ADA" -- it's named after "Ada Lovelace"; it is not an acronym.
A subtype is compatible with its base type, so you can mix operands of the base type with operands of the base type. For example:
Since this is a subtype, you can (for example) add
1
to a weekday to get the next weekday.A derived type is a completely separate type that has the same characteristics as its base type. You cannot mix operands of a derived type with operands of the base type. If, for example, you used:
Then you would not be able to add an integer to a weekday to get another weekday. To do manipulations on a derived type, you'd normally define those manipulations yourself (e.g., create a package). At the same time, a derived type does "inherit" all the operations of its base type (even some that may not make sense) so you do still get addition.
来自 Wikibook:
给定类型的子类型将彼此兼容。
派生类型是从现有类型创建的一种新的、成熟的类型。与任何其他类型一样,它与其父类型不兼容;但是,它继承了为父类型定义的原始操作。
From Wikibooks:
Subtypes of a given type will be compatible with each other.
A derived type is a new, full-blown type created from an existing one. Like any other type, it is incompatible with its parent; however, it inherits the primitive operations defined for the parent type.
基本区别在于派生类型是不同类型。您不能将其中一个分配给另一个,或在表达式中一起使用它们。另一方面,子类型与其原始类型是赋值兼容的。您可以将它们一起使用,而无需输入任何类型修改代码。
不过,子类型的范围比基类型窄,因此可能会进行范围检查(我相信可以从中引发 Constraint_Error )。所以你还是要小心。
The basic difference is that a derived type is a different type. You cannot just assign one to the other, or use them together in an expression. A subtype on the other hand is assignment-compatible with its original type. You use them together without having to enter any type-munging code.
The subtype will have a narrower range than the base type though, so there may be range checks (from which I believe Constraint_Error can be rasied). So you do still have to be careful.