Resolving procedure confusion when using OOP

2019-03-03 14:57发布

I am writing a vector type in Fortran and am getting very confused.

Suppose I have the following derived type

Type (Vector)
Real :: x, y
Contains  
  Procedure :: vector_smul
End Type 

Function vector_smul  &
  (                   &
    va, vb            &
  )                   &
    Result (c)

  Real :: c
  Class (Vector), Intent (In) :: va, vb

  c = (va%x + vb%x) + (va%y * vb%y)

End Function vector_smul

However when I use

Type (Vectors)
Real :: x, y
Contains  
  Procedure :: smul => vector_smul
End Type 

I get an error when I use

Program Test
  Use Vector
  Implicit None
  Real :: c
  Type (Vector) :: va, vb 
  c = smul (va, vb)
End Program

标签: oop fortran
1条回答
走好不送
2楼-- · 2019-03-03 15:40

You are just defining a type-bound procedure xyz%smul that points to vector_smul! The original module procedure vector_smul is not effected!

To stay in the terminology of the Fortran Standard (2008, ch. 4.5.5), smul is the binding name for the procedure name vector_smul. You still can access the procedure itself.

You can "rename" the function when using it in the main program:

Program Test
  Use Vector, only: Vector, smul => vector_smul
  Implicit None
  Real :: c
  Type (Vector) :: va, vb 
  c = smul (va, vb)
End Program

[Although it is not possible to have the same name for the type different and the module, i.e. not name them both Vector...]

Take a look at the corresponding topic at the Fortran Wiki...

查看更多
登录 后发表回答