2017-01-24 7 views
1

this code Betrachten wir das ein Tutorial für die objektorientierte Programmierung in Fortran ist:Wo ist der Klassenkonstruktor?

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 

ich einen Konstruktor für die Klasse nicht sehen, so wie funktioniert c = Circle(1.5) eigentlich? Was, wenn es mehr Felder für die Klasse gibt, wie kann ich einen Konstruktor erstellen, der sie standardmäßig initialisiert?

Antwort

2

Jeder benutzerdefinierte abgeleitete Typ in Fortran hat einen Standardstrukturkonstruktor. Seine Argumente sind einfach alle Komponenten des abgeleiteten Typs in der Reihenfolge, wie sie deklariert sind.

Bestimmte Komponententypen können im Standardkonstruktor optional sein, z. B. die standardmäßig initialisierten Komponenten oder zuweisbaren Komponenten.

Der Strukturkonstruktor ist eine Funktion, die ein Objekt des abgeleiteten Typs zurückgibt und nach dem abgeleiteten Typ benannt ist. Es may be overloaded von einem benutzerdefinierten Strukturkonstruktor.


„Was passiert, wenn es mehr Felder für die Klasse ist, wie kann ich einen Konstruktor erstellen, die sie standardmäßig initialisieren?“

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) 

sind alle legal. Die Komponenten sind das Argument des Standardkonstruktors in der Reihenfolge, wie sie deklariert sind, aber einige von ihnen sind optional. (Beachten Sie, gfortran 4.8 nicht den obigen Code kompilieren, aber es ist falsch)

+0

Danke, ich möchte ein Timer-Objekt erstellen, ist es möglich, System_Clock aufrufen und Werte zuweisen, dass die Haltezahl max Feld und Zählrate in ein Konstruktor, der automatisch ausgeführt wird? – Saeid

+1

, die für einen benutzerdefinierten Konstruktor http://stackoverflow.com/questions/4262253/how-to-override-a-structure-constructor-in-fortran oder vielleicht auch nicht wie eine Aufgabe klingt. Ich bin mir nicht sicher, was du genau meinst. –