Fortran Coder

查看: 13953|回复: 6
打印 上一主题 下一主题

[派生类型] 向派生数据类型中赋值出现奇怪的错误,谢谢各位高手

[复制链接]

490

帖子

4

主题

0

精华

大宗师

F 币
3298 元
贡献
1948 点

水王勋章元老勋章热心勋章

楼主
发表于 2018-2-8 15:17:52 | 显示全部楼层
需要用到面向对象编程的内容,类似于C++的构造函数
[Fortran] 纯文本查看 复制代码
module example
    implicit none
    type:: base
        integer:: nlen=2
        real, allocatable:: array(:)
    end type
    interface base
        module procedure new_base
        module procedure new_base_list
    end interface
    contains
            function new_base(nlen)
                implicit none
                integer, intent(in), optional:: nlen
                type(base):: new_base
                write(*, "('Call constructor: new_base(nlen)')")
                if (present(nlen)) then
                    if (0 < nlen) then
                        new_base%nlen = nlen
                        write(*, '(2x, "User defined length:", 1x, i4)') nlen
                    else
                        write(*, '(2x, "Negetive input and use default value 2")')
                    endif
                else
                    write(*, '(2x, "Default length: 2")')
                end if
                allocate(new_base%array(new_base%nlen))
            end function

            function new_base_list(array) result(new_base)
                implicit none
                real, intent(in):: array(:)
                type(base):: new_base
                write(*, "('Call constructor: new_base_list(array)')")
                new_base%nlen = size(array)
                allocate(new_base%array(new_base%nlen))
                new_base%array = array
                write(*, "(2x, 'Array:', *(f7.2))")new_base%array
            end function
end module

program oop
use example
implicit none
type(base):: a1, a2, a3, a4
a1 = base()
a2 = base(nlen=6)
a3 = base(-2)
a4 = base([1E1, 3E2, 5E0, 7E0, 9E1])
end program
您需要登录后才可以回帖 登录 | 极速注册

本版积分规则

捐赠本站|Archiver|关于我们 About Us|小黑屋|Fcode ( 京ICP备18005632-2号 )

GMT+8, 2024-5-6 22:03

Powered by Tencent X3.4

© 2013-2024 Tencent

快速回复 返回顶部 返回列表