需要用到面向对象编程的内容,类似于C++的构造函数
[Fortran] 纯文本查看 复制代码 module example
implicit none
type:: base
integer:: nlen=2
real, allocatable:: array(:)
end type
interface base
module procedure new_base
module procedure new_base_list
end interface
contains
function new_base(nlen)
implicit none
integer, intent(in), optional:: nlen
type(base):: new_base
write(*, "('Call constructor: new_base(nlen)')")
if (present(nlen)) then
if (0 < nlen) then
new_base%nlen = nlen
write(*, '(2x, "User defined length:", 1x, i4)') nlen
else
write(*, '(2x, "Negetive input and use default value 2")')
endif
else
write(*, '(2x, "Default length: 2")')
end if
allocate(new_base%array(new_base%nlen))
end function
function new_base_list(array) result(new_base)
implicit none
real, intent(in):: array(:)
type(base):: new_base
write(*, "('Call constructor: new_base_list(array)')")
new_base%nlen = size(array)
allocate(new_base%array(new_base%nlen))
new_base%array = array
write(*, "(2x, 'Array:', *(f7.2))")new_base%array
end function
end module
program oop
use example
implicit none
type(base):: a1, a2, a3, a4
a1 = base()
a2 = base(nlen=6)
a3 = base(-2)
a4 = base([1E1, 3E2, 5E0, 7E0, 9E1])
end program |