【问题标题】:Is it possible to implement an "abstract" variable inside a type in Fortran 2003?是否可以在 Fortran 2003 中的类型内实现“抽象”变量?
【发布时间】:2013-10-15 21:07:23
【问题描述】:

我想写一个抽象类型

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

我想在数组的抽象类型中有一个占位符,这样它就可以在扩展类型中被覆盖或重新定义,比如

type, extends(Vehicle) :: Bike
     allocate(Wheels(2))
    contains
     procedure :: VehicleWeight => BikeWeight
end type Bike

    type, extends(Vehicle) :: Car
     allocate(Wheels(4))
    contains
     procedure :: VehicleWeight => CarWeight
end type Car

GCC 编译器抱怨(我猜是正确的),我能找到的解决这个问题的唯一方法就是不在抽象类型中声明可分配函数,而是直接在类型内以正确的大小声明变量。 不过,我希望有一种占位符来强制执行 Wheels 描述的基本属性(原型)。我

【问题讨论】:

    标签: fortran prototype abstract-class


    【解决方案1】:

    组件的分配是一个可执行的操作——它需要出现在源代码的可执行部分中。考虑类似的事情:

    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
    

    在 Fortran 2008 中,这可以通过以下简单方式使用:

    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)
    

    在 Fortran 2003 中,不支持对多态对象的内在赋值。需要使用解决方法,例如在 ALLOCATE 语句中使用 SOURCE 说明符。

    对组件和过程适当地应用公共和私有可以进一步引导和约束客户端代码以正确的方式与类型交互。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-02
      • 2012-02-25
      • 1970-01-01
      • 2012-02-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多