Is it possible to implement an “abstract” variable inside a type in Fortran 2003?

后端 未结 1 652
误落风尘
误落风尘 2021-01-13 22:16

I would like to write an abstract type

type, abstract :: Vehicle
    real, dimension(:), allocatable:: Wheels 
    contains
     procedure (Compute_Weight),         


        
相关标签:
1条回答
  • 2021-01-13 22:57

    Allocation of an component is an executable action - it needs to appear in an executable part of your source. Consider something like:

    type, abstract :: vehicle
      real, dimension(:), allocatable :: wheels
      ...
    end type
    
    type, extends(vehicle) :: bike
      ...
    end type bike
    
    type, extends(vehicle) :: car
      ...
    end type car
    
    interface bike
      procedure bike_constructor
    end interface bike
    
    interface car
      procedure car_constructor
    end interface car
    
    ...
    
    function bike_constructor()
      type(bike) :: bike_constructor
      allocate(bike_constructor%wheels(2))
      ...
    end function bike_constructor
    
    function car_constructor()
      type(car) :: car_constructor
      allocate(car_constructor%wheels(4))
      ...
    end function car_constructor
    

    In Fortran 2008, this can be used in the following straightforward manner:

    class(vehicle), allocatable :: obj
    IF (i_feel_like_some_exercise) THEN
      obj = bike()
    ELSE
      obj = car()
    END IF
    PRINT "('My object has ',I0,' wheels!')", SIZE(obj%wheels)
    

    In Fortran 2003, intrinsic assignment to a polymorphic object is not supported. Workarounds such as using a SOURCE specifier in an ALLOCATE statement need to be used.

    Appropriate application of public and private to components and procedures can further guide and constrain client code to interact with the types in the right way.

    0 讨论(0)
提交回复
热议问题