參考:http://blog.csdn.net/kissdeath/article/details/2060573
Delphi程序不僅可以用於數值處理,還更廣泛的用於處理非數值的數據。例如:性別、月份、星期幾、顏色、單位名、學歷、職業等。
1.枚舉類型的定義
格式:type 枚舉類型標識符 = (標識符1, 標識符2, ..., 標識符n)
2.枚舉類型數據特點
1)枚舉元素只能是標識符
例如,下面的定義是合法的
type
days = (sun, mon, tue, wed, thu, fri, sat);
colors= (red, yellow, blue, white, black, green);
而下面的類型定義是錯誤的
type
colortype= ('red', 'yellow', 'blue', 'white');
numbers= (1,3,4,5,6);
定義枚舉類型的時候列出所有枚舉元素構成了這種枚舉類型的值域(取值范圍)
2)枚舉類型屬於順序類型
根據定義類型時各枚舉類型的排列順序確定他們的序號,且序號從0開始
例如,定義
type
days=(sun,mon,tue,wed,thu,fri,sat);
則,ord(sun)=0, ord(mon)=1,...,以此類推
枚舉類型中的第一個元素無前驅,最有一個元素無后繼
3)同一個枚舉元素不能出現在兩個或兩個以上的枚舉類型定義中。如下的定義是錯誤的
type
color1 = (red, yellow, white);
color2 = (blue, red, black);
因為red屬於枚舉類型color1和枚舉類型color2
4)枚舉類型變量只能進行賦值運算和關系運算,不能進行算術運算和邏輯運算
在枚舉元素比較的時候,實際上是對其序號的比較
例如定義如下
type
days = (sun, mon, tue, wed, thu, fri, sat);
colors = (red, yellow, blue, white, black, green);
var
color : colors;
weekday : days;
則下面的語句是合法的
weekday := mon;
if weekday=sun then
write('reset');
而下面的語句是不合法的
mon := 1; //錯把枚舉值當成變量名 weekday := blue; //枚舉值blue不屬於枚舉變量weekday的值域 read(color); //枚舉類型變量不能用讀語句進行賦值 write(weekday); writeln(blue); //不能通過寫語句輸出枚舉類型的變量值和枚舉值
5)可以把變量的說明與類型的定義合並在一起,比如
var
hoilday, workday : (sun, mon, tue, wed, thu, fri, sat);
color : (red, yellow, blue, white, black, green);
對枚舉數據的輸入與輸出可通過間接方式進行。輸入時,一般可輸入一個代碼,通過程序進行轉換,輸出時,也只是打印出與枚舉元素相對應的字符串。這在后面會有實例展示
3.枚舉類型的應用
例,輸入今天是星期幾的序號,輸出明天是星期幾的英文單詞(星期天序號為0)
type
weekday = (sun, mon, tue, wed, thu, fri, sat);
var
i : integer;
today, tomorrow : weekday;
begin
writeln('What date is it');
readln(i);
case i of {根據輸入轉換成枚舉類型}
0 : today:=sun;
1 : today:=mon;
2 : today:=tue;
3 : today:=wed;
4 : today:=thu;
5 : today:=fri;
6 : today:=sat;
endl
if today=sat then
tomorrow := sun
else
tomorrow := succ(today); //succ()是求這個枚舉元素的后繼
write('The tomorrow is ');
case tomorrow of
sun : writeln('sunday');
mon : writeln('monday');
tue : writeln('tuesday');
wed : writeln('wednesday');
thu : writeln('thursday');
fri : writeln('friday');
sat : writeln('saturday');
end;
end.
枚舉類型是一種有序類型,所以枚舉類型的變量可以作為循環變量。
學習枚舉類型的時候,注意枚舉元素和變量的區別,以及枚舉與變量的輸入輸出方法的處理
