What is the point of renaming Types in Ada

拜拜、爱过 提交于 2019-12-02 05:40:47

问题


In Ada, I have commonly seen something like this:

type Number is new Integer;

What is the point of this? Can't you just be happy with an Integer? I have also seen code such as:

type Small_Number is range 1..5;

This makes sense to me; I can see why this would be useful. But why, in any case would you choose to use the former example?


回答1:


More commonly I have seen code like this:

Type Pounds  is new Integer;
Type Euros   is new Integer;
Type Dollars is new Integer;

This means that you are not going to assign your Pounds to Euros to Dollars by accident.

If you want to convert between the two you would need to either do an explicit cast, or write a conversion routine, both of which would take the applicable exchange rate into account.

(Now I think about it further, Float would have been better than Integer for this example!)




回答2:


The point is that Number is a new type, quite distinct from Integer.

That means more control over parameters and such since you cannot use an Integer where a Number is required; this aids with encapsulation.

It's quite plausible that you want to keep this level of control and perhaps plan for the future where you may end up with Number being totally different from Integer.




回答3:


I agree that

type Number is new Integer;

(which is not a "renaming" of a type) looks like bad style, but there may be a perfectly good reason for it. For example:

  • You want Number to be a distinct type, but with the same range as Integer.
  • You want Number to match the range of an array type with an Integer derived index.


来源:https://stackoverflow.com/questions/23220161/what-is-the-point-of-renaming-types-in-ada

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!