0

我尝试了以下代码,发现 OPTIONAL 关键字不起作用。编译没问题,但是会提示运行时错误。

我知道通常应该在模块中使用 INTERFACE 来为例程提供足够的信息。我也尝试过,但无论我把接口放在哪里都无法完成编译。

我已经阅读了一些在 TYPE 声明中使用 OPTIONAL 的代码。https://www.pgroup.com/lit/articles/insider/v3n1a3.htm

现在我使用的是intel visual fortran,那有什么区别吗?

module testA_m
implicit none

type :: onion_c
    contains
    procedure :: testA
end type

contains

subroutine testA(this, a,b)
    implicit none
    class(onion_c) :: this
    real*8 :: a
    real*8, optional :: b

    write(*,*) a,b
end subroutine    
end module

program main
call testIt()
end program

subroutine testIt()
use testA_m
implicit none
type(onion_c) :: onion
real*8 :: c1 
real*8 :: c2

c1 = 1.0d0
c2 = 2.0d0
call onion.testA(c1)

end subroutine
4

3 回答 3

1

好吧,您正在尝试 print b,它没有传递给子例程。因此访问冲突。

您应该首先检查b

subroutine testA(this, a,b)
    implicit none
    class(onion_c) :: this
    real*8 :: a
    real*8, optional :: b

    if ( present(b) ) then
      write(*,*) a,b
    else
      write(*,*) a
    endif
end subroutine   
于 2015-03-30T08:20:17.190 回答
0

也许我需要另一个变量来进行实际操作。像下面这样。

我仍然期待更好的解决方案b直接使用。

subroutine testA(this, a,b)
    implicit none
    class(onion_c)   :: this
    real*8           :: a
    real*8, optional :: b
    real*8           :: bUsed

    if ( present(b) ) then
        bUsed = b
        write(*,*) a,bUsed
    else
        bUsed = 2.00d0
        write(*,*) a,bUsed
    endif
end subroutine   
于 2015-03-31T04:05:21.700 回答
0

因为 Fortran 不支持类似的程序

subroutine testA( this, a, b=10.0d0 )

我通常在一个通用头文件中定义如下宏

#define _optval_(x,xopt,default)   x = default; if (present(xopt)) x = xopt

然后在子程序的顶部使用它

subroutine testA(this, a,b_)
class(onion_c)   :: this
real*8           :: a
real*8, optional :: b_
real*8  b

_optval_( b, b_, 10.0d0 )  !! use only b from here on

虽然这与写几个 IF 结构没有本质区别,但我觉得它更方便一些(至少对于简单的变量),因为在后续代码中无需担心 b 是否可选。(但坦率地说,我希望 Fortran2020 左右会支持类似于第一个示例的语法......)

于 2015-05-12T16:49:32.683 回答