派生类型的构造方法

老师

我正在尝试为抽象派生类型编写一个构造函数,解决另一个问题,但看来它不起作用,或者更好,根本没有调用它。

目的是使运行时多态性可以设置动物的正确腿数。

这是两个模块:

动物

module animal_module
    implicit none

    type, abstract :: animal
        private
        integer, public :: nlegs = -1
    contains
        procedure :: legs
    end type animal

contains

    function legs(this) result(n)
        class(animal), intent(in) :: this
        integer :: n

        n = this%nlegs
    end function legs

module cat_module
    use animal_module, only : animal
    implicit none

    type, extends(animal) :: cat
        private
    contains
        procedure :: setlegs => setlegs
    end type cat

    interface cat
        module procedure init_cat
    end interface cat

contains

    type(cat) function init_cat(this)
        class(cat), intent(inout) :: this
        print *, "Cat!"
        this%nlegs = -4
    end function init_cat

主程序

program oo
    use animal_module
    use cat_module
    implicit none

    type(cat) :: c
    type(bee) :: b

    character(len = 3) :: what = "cat"

    class(animal), allocatable :: q

    select case(what)
    case("cat")
        print *, "you will see a cat"
        allocate(cat :: q)
        q = cat() ! <----- this line does not change anything

    case default
        print *, "ohnoes, nothing is prepared!"
        stop 1
    end select

    print *, "this animal has ", q%legs(), " legs."
    print *, "cat  animal has ", c%legs(), " legs."
end program

根本没有调用构造函数,并且支路数量仍为-1

法国

类型的可用非默认构造函数cat由模块procedure提供init_cat您定义的此功能如下

type(cat) function init_cat(this)
    class(cat), intent(inout) :: this
end function init_cat

这是一个带有个自变量的函数class(cat)在以后的参考中

q = cat()

泛型下没有cat与该引用匹配的特定函数:该函数init_cat不接受无参数引用。而是使用默认的结构构造函数。

您必须cat以与init_cat接口相匹配的方式引用泛型,以调用该特定功能。

您想将init_cat功能更改

type(cat) function init_cat()
    ! print*, "Making a cat"
    init_cat%nlegs = -4
end function init_cat

然后,您可以q=cat()根据需要进行引用

请注意,在原始版本中,您试图“构造”一个cat实例,但是没有返回此构造的实体作为函数结果。相反,您正在修改自变量(已构造)。打算使用结构构造函数返回此类有用的东西。

另请注意,您不需要

allocate (cat :: q)
q = cat()

的固有分配q已处理q的分配。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章