2

下面的示例使用Fortran 2003定义无限多态指针和基于select type构造后面的变量类型执行操作的功能。该子例程handleP根据参数的类型打印参数的值。

program example
    implicit none
    type name
        character(22) :: n
    end type

    character(len=7) :: mystring
    mystring = 'Initial'

    call handleP(mystring)
    call handleP('Initial')
    call handleP(name('Initial'))

    contains

        subroutine handleP(p)
            class(*), intent(in) :: p

            select type(p)
            type is (character(len=*))
                write(*,*) len(p), ': ', p
            class is (name)
                write(*,*) len(p%n), ': ', p%n
            class default
                write(*,*) 'Unknown type'
            end select
        end subroutine

end program example

gfortran使用4.8 版编译会得到以下输出:

       7 : Initial
       0 :
      22 : Initial

因此,call handleP(mystring)一切都按预期工作,但call handleP('Initial')打印失败。带type(name)参数调用也有效。

call handleP('Initial')gfortran错误的行为还是我做错了什么?如果它是一个错误,我能做些什么来防止它?

4

2 回答 2

2

我只想让大家知道,该问题已在当前 MinGW 安装附带的 gFortran 4.9.3-1 下得到解决。

于 2016-06-03T19:09:27.283 回答
0

这可能是你想要的:

program example
    implicit none
    type name1
        character(22) :: n
    end type

    character(len=7) :: mystring
    mystring = 'Initial'

    call handleP(mystring)
    call handleP('Initial')
    call handleP(name1('Initial'))

    contains

        subroutine handleP(p)
            class(*), intent(in) :: p

            select type(p)
            type is (character(len=*))
                write(*,*) len(p), ': ', p
            class is (name1)
                write(*,*) len(trim(adjustl(p%n))), ': ', p%n
            class default
                write(*,*) 'Unknown type'
            end select
        end subroutine

end program example

第二次调用不起作用,因为“初始”不是变量。之前的 22 只是您在类型声明中定义的长度。所以我调整了它的长度。

于 2014-06-02T14:15:15.417 回答