我有点通过以下程序指针作为伪参数
module test
implicit none
type TestType
integer :: i
end type
contains
subroutine foo(test)
type (TestType), intent(out) :: test
test%i = 5
end subroutine
subroutine bar(test)
type (TestType), intent(out) :: test
test%i = 6
end subroutine
end module
program hello
use test
type(TestType) :: t
call foo(t)
print *, t%i
call bar(t)
print *, t%i
end program hello
及其衍生物困惑。更多关于这些。正如我们所知道的那样,Fortran将常规参数作为参考传递来传递,这意味着在foo
和bar
这两个虚拟参数test
上出现的实体与在program hello
中的栈中授予的内存空间相同。到现在为止还挺好。
假设我在program hello
中定义了type(TestType) :: t
作为指针并分配它。
program hello
use test
type(TestType), pointer :: t
allocate(t)
call foo(t)
print *, t%i
call bar(t)
print *, t%i
deallocate(t)
end program hello
代码和以前一样工作,唯一的区别是对象没有在堆栈上分配,而是在堆上。
现在假设回到堆栈分配程序和子程序栏,而不是定义为
subroutine bar(test)
type (TestType), pointer :: test
test%i = 6
end subroutine
程序不会再编译,因为你必须使用堆分配的版本,使其工作,或者更准确的是,当例程被定义为接受指针作为伪参数时,必须将指针传递给例程。另一方面,如果伪参数不包含关键字pointer
,则该例程将接受指针和非指针。
这让我想知道......声明一个虚拟参数指针有什么用处?
@Rook:去吧... :) – 2010-10-15 12:18:32