1
考慮this code這是Fortran的面向對象編程教程:類構造函數在哪裏?
module class_Circle
implicit none
private
public :: Circle, circle_area, circle_print
real :: pi = 3.1415926535897931d0 ! Class-wide private constant
type Circle
real :: radius
end type Circle
contains
function circle_area(this) result(area)
type(Circle), intent(in) :: this
real :: area
area = pi * this%radius**2
end function circle_area
subroutine circle_print(this)
type(Circle), intent(in) :: this
real :: area
area = circle_area(this) ! Call the circle_area function
print *, 'Circle: r = ', this%radius, ' area = ', area
end subroutine circle_print
end module class_Circle
program circle_test
use class_Circle
implicit none
type(Circle) :: c ! Declare a variable of type Circle.
c = Circle(1.5) ! Use the implicit constructor, radius = 1.5.
call circle_print(c) ! Call a class subroutine
end program circle_test
我沒有看到該類任何構造函數,因此如何c = Circle(1.5)
實際工作?如果該類有更多的字段,我該如何創建一個默認初始化它們的構造函數呢?
謝謝,我想創建一個計時器對象,是否有可能調用system_clock並將值分配給字段,保持計數最大值和計數率在一個自動執行的構造函數? – Saeid
這聽起來像是一個用戶定義的構造函數的任務http://stackoverflow.com/questions/4262253/how-to-override-a-structure-constructor-in-fortran或者可能不是。我不確定你的意思。 –