开发者

Invalid types for operand "+" Ada 95

I have defined two integer ranges in ans spec file of Ada95, as follows:

type year is new integer range 1996..2100;
type month is new integer range 1..12;

When i'm compiling the code of the body file, i have a code line like this:

....
    key: integer;
begin 
    key:= (yearVal*100) + monthVal;

YearVal is a year type and monthVal is a month type, i have the following error

compiling:invalid o开发者_如何转开发perand types for operator "+"

how can i add this values to obtain a integer? Thanks!


When you use the construction X is new, you are creating a new type. It is incompatible with other types, and should exist in sort of its own universe where it interacts with nothing but other X types.

This means you really have to think out your typing strategy beforehand, to make sure all the objects you might want to perform math on are of the same type (operating in the same universe).

If instead what you wanted to do was put a bound on the allowable range of X, but allow it to operate in math expressions with other integers, you should instead use subtypes, like so:

subtype year is integer range 1996..2100;

(note no new).

However, if you really do want Years and Months to be in their own incompatible universes, but have this one internal case where for conversions you need to do math with them, what you can do is convert them to integers in this one case.

key:= (Integer(yearVal)*100) + Integer(monthVal);

Again, this would be a major PITA if you have to do it every time you use those objects for anything, so if that's the case, they should be subtypes of the same type (probably Integer).


Use a type conversion.


As stated earlier, either use type conversion or use subtype instead of type. In case you haven't used subtype before, here's how:

   subtype year is Integer range 1996 .. 2100;
   subtype month is Integer range 1 .. 12;
   yearVal : year;
   monthVal : month;

Then you can freely do:

   key : Integer;
begin
   key := (yearVal*100) + monthVal;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜