By Nana
Struct 結構體
「Struct」本身是C語言的保留字(keyword) 是物件導向語言中「類別(class)」的前身
Struct是使用者自定義的綜合體
一個員工Employee =
- 姓名(String)
- 年齡(int)
- 到職日(DateTime)
那麼可以說這筆員工資料就是一個結構體。
它不是一個新創造的型態
我們只是「綁定」了這些String, Int, DateTime 變成自定義名稱的、結構化的資料型態
// 這麼一來我們就可以直接用宣告的方式來使用它: struct Employee 王小明 struct Employee 陳小冬 struct Employee 張小華
通常我們會直接建立一個class確保安全性與功能性
BUT
有時候直接操作資料塊(Block)也是很有用的!
' Visual Basic Example of Swapping Two Groups of Data the Hard Way
' swap new and old employee data
previousOldName = oldName
previousOldAddress = oldAddress
previousOldPhone = oldPhone
previousOldSsn = oldSsn
previousOldGender = oldGender
previousOldSalary = oldSalary
oldName = newName
oldAddress = newAddress
oldPhone = newPhone
oldSsn = newSsn
oldGender = newGender
oldSalary = newSalary
newName = previousOldName
newAddress = previousOldAddress
newPhone = previousOldPhone
newSsn = previousOldSsn
newGender = previousOldGender
newSalary = previousOldSalary
' Visual Basic Example of Declaring Structures
Structure Employee
name As String
address As String
phone As String
ssn As String
gender As String
salary As long
End Structure
Dim newEmployee As Employee
Dim oldEmployee As Employee
Dim previousOldEmployee As Employee
' 接著只需要用簡單的三句話即可替換新舊資料:
previousOldEmployee = oldEmployee
oldEmployee = newEmployee
newEmployee = previousOldEmployee
HardWayRoutine( name, address, phone, ssn, gender, salary )
EasyWayRoutine( employee )
在建立結構時就已經將相關的資料分組在一起, 因此修改結構較簡單。
「變更往往會產生錯誤,因此變更越少,錯誤也就越少」