好吧,所以我可能会以某种不应该使用的方式使用某些东西,但这是我的问题。我试图创建一个可以包含扩展单个父类型的不同类型的数组。要做到这一点(通过这篇文章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'在每次形状之后。所以我试图使用下面的程序main。
#define shapes(m) shapes(m)%s
这当然很有效,除了分配(形状(3))'这打破了代码。我对如何避免这种情况感到茫然。
所以,可能有问题的是,是否有更好的方法来执行继承变量数组,一种避免在分配语句期间中断的方法,或另一种解决此问题的方法。另外,如何使用fpp的合适指南会很有帮助。 https://software.intel.com/en-us/node/510271是我目前正在使用的内容,如果我之前曾使用过预处理器,我确信它会有用,但对于那些没有使用预处理器的人来说却没用。
我正在使用英特尔Visual Fortran 2015和VS2012。
答案 0 :(得分:0)
shapes(m)
和shapes(m)%s
在Fortran中具有含义,因此将shapes(m)
重新定义为shapes(m)%s
会明显破坏代码。在定义宏时应使用非Fortran关键字,或者至少使用其他地方不存在的单词。例如,
#define SHAPES(m) shapes(m)%s
(通常使用带有预处理器宏的大写字母)或者如果你坚持保存按键,则更短。话虽这么说,使用预处理器缩短代码可能不是最好的风格,可能会损害可读性。我建议使用文本编辑器的功能轻松插入相关的代码位。