是否有可能实现一个“抽象"?Fortran 2003 中类型中的变量? [英] Is it possible to implement an "abstract" variable inside a type in Fortran 2003?

查看:27
本文介绍了是否有可能实现一个“抽象"?Fortran 2003 中类型中的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一个抽象类型

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

也就是说,我希望在数组的抽象类型中有一个占位符,这样它就可以在扩展类型中用类似的东西覆盖或重新定义

that is I'd like to have a placeholder in the abstract type for an array in such a way that it could be overridden or redefined in the extended type with something like

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

GCC compiler complains (rightfully I guess), and the onlys solution I could find to this problem is just to not declare the allocatable function in the abstract type and declare the variable directly with the correct size inside the type. Nevertheless I would like to have a sort of placeholder to enforce the implementation of the fundamental property descrived by Wheels (a prototype). I

推荐答案

组件的分配是一个可执行操作 - 它需要出现在源代码的可执行部分中.考虑如下:

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

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

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)

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

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.

这篇关于是否有可能实现一个“抽象"?Fortran 2003 中类型中的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆