好吧,我可能以不应该的方式使用了某些东西,但这是我的问题。我正在尝试制作一个数组,该数组可以容纳扩展单个父类型的不同类型。为此(通过这篇文章 https://software.intel.com/en-us/forums/topic/280765 ),建议我按如下方式进行。
program main
implicit none
type shape
integer :: x,y
end type shape
type shape_c
class(shape), pointer :: s
end type shape_c
type, extends(shape) :: rectangle
integer :: w,h
end type rectangle
type, extends(shape) :: circle
integer :: r
end type
type(rectangle) :: r
type(circle) :: c
type(shape) :: s
class(shape_c), dimension(:), allocatable :: shapes
r = initRect()
c = initCircle()
s = initShape()
allocate(shapes(3))
shapes(1)%s => r
shapes(2)%s => c
shapes(3)%s => s
write(*,*) shapes(1)%s%x * shapes(2)%s%x * shapes(3)%s%x
end program main
在那篇文章的结尾,有人建议我使用 fpp 以避免每次都必须在形状后写“%s”。所以我尝试使用下面的主程序。
#define shapes(m) shapes(m)%s
这当然很好用,除非“allocate(shapes(3))”破坏了代码。我不知道如何避免这种情况发生。
所以,可能的问题是,是否有更好的方法来处理继承变量的数组,避免在分配语句期间中断的方法,或解决此问题的其他方法。此外,关于如何使用 fpp 的体面指南也会有所帮助。 https://software.intel.com/en-us/node/510271是我目前正在使用的东西,如果我以前曾经使用过预处理器,我相信它会有所帮助,但对于没有使用过预处理器的人来说就没那么有用了。
我正在使用 Intel Visual Fortran 2015 和 VS2012。
最佳答案
shapes(m)
和 shapes(m)%s
在 Fortran 中都有含义,因此重新定义所有 shapes(m)
as shapes(m)%s
显然破坏了代码。定义宏时应使用非 Fortran 关键字,或至少使用别处不存在的词。例如,
#define SHAPES(m) shapes(m)%s
(通常将大写字母与预处理器宏一起使用)或者如果您坚持要保存击键,则使用更短的名称。也就是说,使用预处理器来缩短代码可能不是最好的方式,而且可能会损害可读性。我建议使用文本编辑器的功能来轻松插入相关代码位。
关于inheritance - Fortran 预处理器指令用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31349288/