2010-12-08

PureBASIC -- 更多的資料結構

摘錄自PureBasic - A Beginner's Guide for Computer Programming, written by Gary Willoughby

謝謝該書作者大方分享!


接著要說明的是更多的資料結構,以便用來存放資料與運用。

關鍵字Structure

使用者可以透過這關鍵字來建立自己的資料結構型態,並且用來設定變數。

Structure PERSONALDETAILS
 FirstName.s
 LastName.s
 Home.s
EndStructure

Me.PERSONALDETAILS

Me\FirstName = "Gary"
Me\LastName = "Willoughby"
Me\Home = "A House"

Debug "First Name: " + Me\FirstName
Debug "Last Name: " + Me\LastName
Debug "Home: " + Me\Home
這裡我們透過Structure...EndStructure來宣告一個新的資料結構,稱為PERSONALDETAILS。並透過Me.PERSONALDETAILS來進行宣告,所以這時候前面的Me就是變數,而後面就是資料型態。而資料取用的方式,上例都說明得很清楚了。你如果想知道你的結構耗用多少記憶體,可以用Sizeof()來瞭解。用法如下:
Structure PERSONALDETAILS
 FirstName.s
 LastName.s
 Home.s
EndStructure
Debug SizeOf(PERSONALDETAILS)
為了避免重複建置結構,所以PureBASIC提供繼承功能,可以參考以下範例:
Structure PERSONALDETAILS
 FirstName.s
 LastName.s
 Home.s
EndStructure

Structure FULLDETAILS Extends PERSONALDETAILS
 Address.s
 Country.s
 ZipCode.s
EndStructure

User.FULLDETAILS

User\FirstName = "John"
User\LastName = "Smith"
User\Home = "A House"
User\Address = "A Street"
User\Country = "UK"
User\ZipCode = "12345"

Debug "Users First Name: " + User\FirstName
Debug "Users Last Name: " + User\LastName
Debug "Users Home: " + User\Home
Debug "Users Address: " + User\Address
Debug "Users Country: " + User\Country
Debug "Users Zip Code: " + User\ZipCode

Structure UNIONSTRUCTURE
是強制讓結構內的變數使用一樣的記憶體位址。範例如下:

Structure UNIONSTRUCTURE
 StructureUnion
  One.l
  Two.l
  Three.l
 EndStructureUnion
EndStructure
Debug SizeOf(UNIONSTRUCTURE)

UnionVariable.UNIONSTRUCTURE

UnionVariable\One = 123
Debug UnionVariable\One

UnionVariable\Three = 456
Debug UnionVariable\One

沒有留言: