2013-05-07 47 views
1

我有一個關於Fortran的問題和 可分配的用戶派生類型的正確分配。可分配的用戶派生類型

這裏是我的代碼:

module polynom_mod 
implicit none 

type monomial 
    integer,dimension(2) :: exponent 
end type 

type polynom 
    real, allocatable, dimension(:) :: coeff 
    type(monomial),allocatable, dimension(:) :: monom 
    logical :: allocated 
!recursive type 
    type(polynom),pointer :: p_dx,p_dy 
contains 
    procedure :: init 
    procedure :: init_dx 
end type 

在這裏我要得到一個類型多項式在那裏我可以做這樣的事情:

p%coeff(1)=1.0 
p%monom(1)%exponent(1)=2 

和喜歡的東西:

p%p_dx%coeff(1)=1.0 
p%p_dx%monom(1)%exponent(1)=2 

所以我寫了一些初始化類型綁定的程序,我可以初始化我的並分配我的 類型:

contains 

function init(this,num) result(stat) 
    implicit none 
    integer, intent(in)  :: num 
    class(polynom),intent(inout) :: this 
    logical :: stat 

    allocate(this%coeff(num)) 
    allocate(this%monom(num)) 

    this%allocated = .TRUE. 
    stat = .TRUE. 
end function 

function init_dx(this,num) result(stat) 
    implicit none 

    integer, intent(in)  :: num 
    class(polynom),intent(inout) :: this 

    logical :: stat 

    allocate(this%p_dx%coeff(num)) 
    allocate(this%p_dx%monom(num)) 

    this%p_dx%allocated = .TRUE. 
    stat = .TRUE. 
end function 
end module 

program testpolytype 
use polynom_mod 

type(polynom) :: p 

if(p%init(2)) then 
    print *,"Polynom allocated!" 
end if 

if(p%p_dx%init_dx(2)) then 
    print *,"Polynom_dx allocated!" 
end if 

端程序

這將gfortran 4.6.3編譯但是當我跑了我有一個分割的錯!

有沒有辦法分配遞歸可分配類型?

回答

2

您的代碼的表面問題是,當計算表達式p%p_dx%init_dx(2)時,指針組件p%p_dx未定義,並且引發了段錯誤。請注意,指針是undefined而不僅僅是沒有關聯

現在我正在努力想出一個快速修復。長期的解決辦法是解決我認爲你的方法存在嚴重缺陷;請注意,這是我的意見,而不是黑白問題,只有在您關心我的意見的情況下才能閱讀。

功能initinit_dx不是免費的副作用,他們確實可以說是幾乎所有的副作用 - 他們返回一個邏輯值,並作爲一個副作用,初始化一個polynom變量。該方案似乎沒有辦法初始化一個polynom沒有評估init也沒有辦法不包成一條語句,如

if (p%init(2)) then 
end if 

你可以,我想,重寫這些初始化功能子程序來評估init,也許一個簽名,如

call initialise_polynom(p,2) 

這將至少從您的代碼中消除不純功能的污點。但更好的方法是編寫一個函數如:

function new_poly(num) 
    implicit none 
    integer, intent(in) :: num 
    type(polynom) :: new_poly 
    allocate(new_poly%coeff(num)) 
    allocate(new_poly%monom(num)) 
    allocate(new_poly%p_dx) 
end function new_poly 

一)返回一個新polynom;和

b)分配組件p_dx;和

c)無副作用。

然後,您可以創建一個新的polynom與作爲

p = new_poly(3) 

這樣的表達,並用一個表達式初始化組件如

p%p_dx = new_poly(3) 
+0

謝謝!對於導致分段錯誤的未初始化指針,你是正確的。 – 2013-05-08 10:47:29

0

回答我的問題,我想出了一個其他解決方案女巫也沒有指針,但它不像馬克斯那麼優雅。

定義的其他類型:

type p_dx 
real, allocatable, dimension(:) :: coeff 
type(monomial),allocatable, dimension(:) :: monom 
logical :: allocated 
end type 

,然後用這個用:

type polynom 
real, allocatable, dimension(:) :: coeff 
type(monomial),allocatable, dimension(:) :: monom 
type(p_dx) :: dx 
logical :: allocated 
contains 
procedure  :: init 
end type 

,所以你可以這樣做:

type(polynom) :: p 

p%init(2) 
p%dx%init_dx(3) 
+0

我會避免一個像'logical :: allocated'這樣的變量,當你將它與內部'alloc'函數混淆時,這隻會導致悲傷和絕望。 – 2013-05-08 11:04:19