gpt4 book ai didi

fortran - 是否可以在 Fortran 2003 中的类型内实现 "abstract"变量?

转载 作者:行者123 更新时间:2023-12-01 09:59:04 25 4
gpt4 key购买 nike

我想写一个抽象类型

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

最佳答案

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

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 说明符。

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

关于fortran - 是否可以在 Fortran 2003 中的类型内实现 "abstract"变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19391094/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com