gpt4 book ai didi

fortran - 引用返回结构/派生类型的函数

转载 作者:行者123 更新时间:2023-12-02 17:04:54 24 4
gpt4 key购买 nike

我正在努力寻找一个简洁的标题,但它并不那么复杂。我有一个返回结构(派生类型)的函数,并且我正在寻找一种简单的方法来在调用该函数时仅引用该结构的一部分(而不复制/指向另一个结构)。

program main

real :: xx = 1.
real :: yy = 2.

! works fine but what I want is to be
! able to return %tx and %ts separately

print *, " tax ", tax(xx,yy)

! just guessing at possible syntax here, but neither works

print *, " tax ", tax%tx(xx,yy)
print *, " tax ", tax(xx,yy)%tx

contains

function tax(x,y)

real :: x, y

type tTax
real :: tx, ty
end type tTax

type(tTax) :: tax

tax%tx = x * 100.
tax%ty = y * 100.

end function tax

end program main

我仅限于 f90/f95 功能集,但也可以随意包含 f2003 答案。

我真的在这里寻找一些简单的东西(如果存在的话)。否则,作为子例程会更好(如果替代方案是将其保留为函数但添加指针、接口(interface)等)。

我还尝试让该函数返回一个二维数组而不是一个结构,并且遇到了相同的基本问题——它可以工作,但我只能打印整个数组,而不能单独打印任何数组部分。

我什至无法猜测那里的语法,因为 () 在 fortran 中用于函数和数组部分(而不是像 python 这样使用 [] 的语言用于索引,因此混合函数和索引是相当自然的,例如 tax(xx,yy)[1,:])。

最佳答案

您可以通过使用函数返回重载派生数据类型的名称来创建用户定义的构造函数。

自由使用 Fortran 2003 标准的associate 构造允许访问特定的类型组件,而无需复制或诉诸容易内存泄漏的指针。

是否有任何特殊原因让您限制自己使用 Fortran 2003?大多数流行的编译器都支持 Fortran 2008 的大部分内容。

以下代码

module mymod

! Explicit typing only
implicit none

! Declare derived data type
type tTax
real :: tx, ty
end type tTax

! User-defined constructor
interface tTax
module procedure tax
end interface tTax

contains

function tax(x, y) result (return_value)
real, intent (in) :: x, y
type (tTax) :: return_value

return_value%tx = x * 100.0
return_value%ty = y * 100.0

end function tax

end module mymod

program main

use mymod

! Explicit typing only
implicit none

real :: xx = 1.0, yy = 2.0
type(tTax) :: foo

print *, " tax ", tax(xx,yy)
print *, " tax ", tTax(xx, yy)

! Invoke the user-defined constructor
foo = tTax(xx, yy)

! Fortran 2003's associate construct
associate( &
tx => foo%tx, &
ty => foo%ty &
)
print *, " tax ", tx, ty
end associate

end program main

产量

gfortran -Wall -o main.exe mymod.f90 main.f90
./main.exe
tax 100.000000 200.000000
tax 100.000000 200.000000
tax 100.000000 200.000000

关于fortran - 引用返回结构/派生类型的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39809698/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com