【发布时间】:2019-10-29 17:14:38
【问题描述】:
我仍然用“面向对象”的风格来围绕 Fortran。
是否可以在派生类型中初始化变量,如果我希望该变量为parameter,该怎么办?
例如,经典的animal、cat、bee 类型集应该设置每只动物的腿数:
动物模块
module animal_module
implicit none
type, abstract :: animal
private
integer, public :: nlegs = -1
contains
...
猫模块
module cat_module
use animal_module, only : animal
implicit none
type, extends(animal) :: cat
private
! error here about redefining nlegs...
integer, public :: nlegs = 4
...
我在网上找到了关键字initial,但我的编译器(英特尔)抱怨该关键字存在语法错误。
附录
我尝试了custom constructor,但显然我无法为派生类型编写一个。这是我的尝试,只针对 cat 类型:
module cat_module
use animal_module, only : animal
implicit none
type, extends(animal) :: cat
private
real :: hidden = 23.
contains
procedure :: setlegs => setlegs
procedure :: speak
end type cat
interface cat
module procedure init_cat
end interface cat
contains
type(cat) function init_cat(this)
class(cat), intent(inout) :: this
this%nlegs = -4
end function init_cat
...
program oo
use animal_module
use cat_module
use bee_module
implicit none
character(len = 3) :: what = "cat"
class(animal), allocatable :: q
select case(what)
case("cat")
print *, "you will see a cat"
allocate(cat :: q)
...
print *, "this animal has ", q%legs(), " legs."
由于animal 类型有integer, public :: nlegs = -1,我希望cat 有-4 腿,但唉,它仍然是-1。
【问题讨论】:
-
问题是,
cat已经有一个名为nlegs的成员变量,因为它是animal的扩展。所以编译器不会让你声明另一个同名成员。我认为您将不得不破解将nlegsforcats设置为4的构造函数。 -
您是想拥有该派生类型的(命名)常量,还是让对象中的组件成为常量?
-
我正在尝试为所有扩展动物的类型提供一个通用字段,在本例中为腿数。
-
@HighPerformanceMark 我同意,虽然我不太了解它们是如何工作的。
-
除了对它们的显式引用之外,不会调用构造函数:没有“分配时的自动构造”。