【发布时间】:2015-09-29 16:56:17
【问题描述】:
好的,所以我可能会以不应该的方式使用某些东西,但这是我的问题。我正在尝试制作一个可以容纳扩展单个父类型的不同类型的数组。为此(通过这篇帖子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
这当然很好用,除非 'allocate(shapes(3))' 会破坏代码。我不知道如何避免这种情况发生。
因此,可能的问题是,是否有更好的方法来处理继承变量的数组,避免在 allocate 语句期间中断的方法,或解决此问题的其他方法。此外,关于如何使用 fpp 的体面指南也会有所帮助。 https://software.intel.com/en-us/node/510271 是我目前正在使用的,如果我以前使用过预处理器,我确信它会有所帮助,但对于没有使用过预处理器的人来说并不是那么有用。
我正在使用 Intel Visual Fortran 2015 和 VS2012。
【问题讨论】:
-
为什么不在分配后定义宏?
-
出于多种原因。首先,据我所知,预处理器必须在声明变量之前定义很多要定义的东西。另一个是即使我可以在任何地方定义它,实际代码也比示例复杂得多,所以它并不像那样清晰。我想我可以写#define after 语句和#undef before 语句,但这听起来像是更糟糕的选择。
-
对不起,别介意不在别处定义。那是我的一个错字。其余的仍然存在。
标签: inheritance fortran preprocessor