派生資料型別和結構體
所謂派生資料型別指的就是,程式設計人員根據資料特征自己定義的、由不同型別資料成分組成的資料型別,它把復雜的資料用一種抽象和形式化的方式描述出來,實際上并未進行實質性的存盤空間分配,這個是我們要注意的,
所謂結構體就是在存盤器內按照派生資料型別描述的內容分配具體的存盤區域,它是派生資料型別資料的具體體現,結構體也稱為記錄,
可以理解為一個抽象,一個具體,
TYPE [::] 派生類名
成員串列
END TYPE [派生類名 ]
舉個栗子:
program stru_test
implicit none
type stu_record !定義的派生資料型別,儲存“學生”身份的屬性
character(len=8) :: name
integer :: score
end type stu_record
type(stu_record) student_A !定義結構體student_A,具有student_record的一切屬性
student_A.name = "zhangsan"
student_A.score = 99
write(*,*) student_A.name,student_A.score
end program stru_test
派生資料型別包含不同型別的資料項成分,是一種新型的資料型別,它能把一些相關的數 據成分匯集在一起,便于對其進行統一處理,
但是我想的是有很多相同型別的結果體,可以理解為集體里很多成員屬性相同,這時就需要一個結構體陣列
program stru_test
implicit none
type stu_record !定義的派生資料型別,儲存“學生”身份的屬性
character(len=10) :: name
integer :: score
end type stu_record
integer,parameter :: nstudent = 30
type(stu_record) student_A !定義結構體student_A,具有student_record的一切屬性
type(stu_record) class_key(nstudent) !定義的結果體陣列,儲存具有“學生”身份的全部成員
student_A.name = "zhang"
student_A.score = 99
write(*,*) student_A.name,student_A.score
class_key(1).name = 'li' !呼叫第一個成員,
class_key(1).score = 60
write(*,*) class_key(1).name,class_key(1).score
end program stru_test
下面就是困擾我一晚上的問題,我想把這個結構體陣列作為全域變數使用,而且成員數目不確定,這就需要nstudent不是一個確定的數,編譯不通過,觸類旁通加上腦洞大開給想出來了:
module stu_module
implicit none
type stu_record !定義的派生資料型別,儲存“學生”身份的屬性
character(len=10) :: name
integer :: score
end type stu_record
integer:: nstudent
type(stu_record) student_A !定義結構體student_A,具有student_record的一切屬性
type(stu_record),allocatable :: class_key(:) !定義的結果體陣列,儲存具有“學生”身份的全部成員
contains
subroutine get_class
allocate(class_key(nstudent))
end subroutine get_class
end module stu_module
program stru_test
use stu_module
implicit none
nstudent = 10
call get_class !呼叫子程式對結構體分配維度
student_A.name = "zhang"
student_A.score = 99
write(*,*) student_A.name,student_A.score
class_key(1).name = 'li' !呼叫第一個成員,
class_key(1).score = 60
write(*,*) 'main:'
write(*,*) class_key(1).name,class_key(1).score
call sub1
deallocate(class_key)
end program stru_test
subroutine sub1
use stu_module
implicit none
class_key(1).score = 100
write(*,*) 'sub1:'
write(*,*) class_key(1).name,class_key(1).score
end subroutine sub1
如上,只是簡單舉個例子,實際應用比這復雜得多,實際上最關鍵的一步實在module里定義可分配大小的結構體陣列,這一點和陣列相似,提一下,get_class里的分配大小也可以放在主程式里定義了nstudent之后,
20201227
參考資料
[1] 白海波.FORTRAN程式設計權威指南[M]. 北京:機械工業出版社,2013
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/241391.html
標籤:區塊鏈
上一篇:E: Failed to fetch http://ppa.launchpad.net/jonathonf/python-3.6/...
