Fortran类指向属性 - 编译器相关结果的指针

时间:2013-12-06 17:05:09

标签: fortran gfortran intel-fortran

我遇到以下代码的问题:

module my_class
   type, public :: my_object
      real, allocatable, private :: a(:)
      real, pointer :: b => null()
   end type my_object
   interface my_object
      module procedure :: init
   end interface my_object
contains
   function init () result ( self )
      type(my_object), target :: self
      allocate( self % a(2) )
      self % a = (/ 1.0, 2.0 /)
      self % b => self % a(1)
   end function init
end module my_class


program test
   use my_class
   type(my_object) :: object
   object = my_object()
   print *, associated( object % b )
   print *, "main: ", object % b
   object % b = 7.
   print *, "main: ", object % b
end program test

属性ab在类构造函数中初始化。预期结果应为:

T
main: 1.00000000
main: 7.00000000

这是我在使用gfortran 4.7.2编译器时获得的,而使用ifort 13.0.1编译的代码会产生以下结果:

T
main:   1.1631523E+33
main:    7.000000

我不明白。我在哪里犯错误?

2 个答案:

答案 0 :(得分:0)

我在ifort 14.0.1中尝试了这个并得到了与gfortran相同的答案。您可能在旧版本中遇到了编译器错误。

答案 1 :(得分:0)

我认为这不是一个错误,代码工作正常,而预期结果不正确。特别是,你预期的“main:1.0000”结果的问题是由于函数“init”,它实际上将数组“a”(因此指针“b”)初始化为1.0,2.0从未被主程序调用。在主程序中,只调用构造函数“my_object()”,而不调用“init”。

至少,这是我的建议。