[英]Fortran derived type constructor defined though C function (II)
以下问题是通过C函数定义的Fortran派生类型构造函数 ,我想到了这个不起作用的示例,使用gfortran 4.9:
module my_module
use iso_c_binding
type, bind(c) :: my_double
real(c_double) :: x
real(c_double) :: y
end type my_double
interface my_double
procedure my_module_fortran_new_my_double
end interface
interface
type(my_double) function my_module_fortran_new_my_double (v) bind ( c )
use iso_c_binding
import :: my_double
real (c_double), intent(in) :: v
end function my_module_fortran_new_my_double
end interface
end module my_module
program main
use my_module
type(my_double) x
x = my_double(12)
end program main
遵循通过C函数定义的Fortran派生类型构造函数的上一个问题,模块定义可以正常工作。 但是,我的编译器无法识别已定义的构造函数。
这是编译器的输出:
$ gfortran -std=f2008 test.f90 -o test.o -c
test.f90:22.6:
x = my_double(12)
1
Error: No initializer for component 'y' given in the structure constructor at (1)!
似乎确实没有考虑我使用的已定义构造函数。 有人可以帮助我理解我做错了什么(再次)吗?
对于特定的构造函数进行匹配
my_double(12)
必须有一个带有接口的程序
type(my_double) function something(i, ...) ...
integer ... :: i
..., optional, ... :: ...
end function
因为给定的单个成分来源是integer
类型。
提供的唯一非默认特定的构造函数是带有一个非可选组件源类型real(c_double)
。
解决的方法有两种:
对于后者:
x = my_double(12._c_double) ! c_double from intrinsic iso_c_binding
值得注意的是为什么会出现此问题。 您可以快乐地尝试
x = my_double(12,13) ! Using the normal constructor
x = my_double(12) ! Using the normal constructor if default
! initialization applies for component y
与隐式构造函数一样,源术语(遵循内部分配规则)也将转换为组件本身的类型/参数。 这种转换不适用于解析泛型的情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.