2017-01-24 39 views
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)實際工作?如果該類有更多的字段,我該如何創建一個默認初始化它們的構造函數呢?

回答

2

Fortran中每個用戶定義的派生類型都有一個默認的結構構造函數。它的參數只是它們聲明的順序中派生類型的所有組件。

某些類型的組件在默認構造函數中可能是可選的,例如默認初始化組件或可分配組件。

結構構造函數是一個函數,它返回派生類型的對象,並在派生類型之後進行命名。它由用戶定義的結構構造函數may be overloaded


「如果有該類多個字段我怎麼可以創建一個構造函數,默認初始化它們?」

type obj 
    real :: a 
    integer :: n = 1 
    real, pointer :: p => null() 
    integer, allocatable :: ia 
end type 


type(obj) :: o 
real, target :: pi = 3.14 

o = obj(1.0) 

o = obj(1.0, 2) 

o = obj(1.0, p = pi) 

o = obj(1.0, ia = 4) 

都是合法的。這些組件是聲明時默認構造函數的順序的參數,但其中一些是可選的。 (請注意,gfortran 4.8不能編譯上面的代碼,但它是錯誤的)

+0

謝謝,我想創建一個計時器對象,是否有可能調用system_clock並將值分配給字段,保持計數最大值和計數率在一個自動執行的構造函數? – Saeid

+1

這聽起來像是一個用戶定義的構造函數的任務http://stackoverflow.com/questions/4262253/how-to-override-a-structure-constructor-in-fortran或者可能不是。我不確定你的意思。 –

相關問題