当前位置 : 主页 > 大数据 > 区块链 >

是否可以在Fortran 2003中的类型中实现“抽象”变量?

来源:互联网 收集:自由互联 发布时间:2021-06-22
我想写一个抽象类型 type, abstract :: Vehicle real, dimension(:), allocatable:: Wheels contains procedure (Compute_Weight), deferred :: VehicleWeightend type Vehicle 我希望在数组的抽象类型中有一个占位符,以便可以在
我想写一个抽象类型

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描述的基本属性(原型).一世

组件的分配是可执行的操作 – 它需要出现在源的可执行部分中.考虑类似的事情:

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说明符的变通方法.

公共和私有组件和程序的适当应用可以进一步指导和约束客户端代码以正确的方式与类型进行交互.

网友评论