第九章 使用列舉和結構建立值型別

2022-04-07 09:02:46 字數 1494 閱讀 2104

使用列舉

可以使用enum關鍵字來建立列舉型別,限制其值只能是一組符號名稱。

宣告列舉

enum season

使用列舉

宣告好列舉之後,可以像使用其他型別的那樣使用它們。假定列舉名稱為season,那麼可以建立season型別的變數,season型別的字段以及season型別的方法引數,如下

enum season

class example

season colorful = season.fall;

console.writeline((int)colorful);//輸出「2」

如果願意,可以將特定整數常量(例如1)和列舉型別的文字常量手動關聯起來

enum season

spring,summer,fall,winter的基礎值將變成1,2,3,4

選擇列舉的基本型別

enum season:short

使用結構

結構是值型別,在棧上儲存。結構可以包含自己的字段、方法和構造器。

宣告結構

struct date

private int year;//字段

private month month;

private int day;

public date(int ccyy, month mm, int dd)//構造器

this.year = ccyy - 1900;

this.month = mm;

this.day = dd -1;

public override string tostring()//方法

string date = string.format(",,",this.month,this.day -1,this.year + 1900);

return date;

public void advancemonth()//方法

this.month++;

if (this.month == month.december + 1)

this.month = month.january;

this.year++;

理解結構和類的區別

①不能為結構宣告預設構造器(無參構造器)。之所以不能為結構宣告自己的預設構造器,是由於編譯器始終都會自動生成乙個。

自己寫的構造器必須顯示初始化所有字段,否則會發生編譯錯誤。

struct time//編譯時錯誤,seconds未初始化

②類的例項字段可以在宣告時初始化,但結構不允許

struct time{

private int hours = 0;//編譯時錯誤

private int minutes;

private int seconds;

複製結構變數

可將結構變數初始化或賦值為另外乙個結構變數,前提是操作符=右側的結構變數已完全初始化。

time now = new time(12,30);

time copy = now;

第九章 結構資料型別實驗

includemain a int i,years,days 0 printf 請輸入年 月 日 scanf d d d a.years,a.months,a.days for i 1 i days a.days printf d年 d月 d日是該年的第 d天。a.years,a.months,a....

第九章 迴圈結構高階

二重迴圈就是乙個迴圈體內包含了另乙個完整的迴圈結構。while與while迴圈巢狀 while 迴圈條件1 while 迴圈條件2 while 迴圈條件1 for與for迴圈巢狀 for 迴圈條件1 迴圈操作1 for 迴圈條件2 迴圈操作2 while與for迴圈巢狀 while 迴圈條件1 迴圈...

資料結構第九章查詢

順序查詢 順序查詢是的最後乙個開始查詢逐個比較 等概率大的情況下平均查詢長度為asl n 1 2 折半查詢 在乙個有11個元素的表中進行折半查詢找到第6個元素需要比較一次 第3 9需要比較2次 折半查詢只限於有序表且限於順序儲存結構 平均查詢長度asl log2 n 1 1 索引順序表 將長度為n的...