我正在寻找一种方法来从后代类访问Fortran类的私有组件(Fortran术语中的派生类型).例如,假设类A具有组件x,它被声明为私有.现在考虑继承自基类A的第二个类B.在这种情况下,类B没有对x的直接访问,因此不允许任何尝试访问B%x.我能想到的两个解决方案是:
(1)声明x为公共.但是,这将使x全局可访问,这会滥用数据隐藏,因此作为问题的可接受解决方案被拒绝.
(2)实现获取/设置A%x的过程,例如A%getX()和A%setX().这不仅麻烦,而且还允许(间接)访问程序中的A%x - 不仅仅是在子类中.
我想要的是一种从A的子类访问A%x的方法,但是否则x应该在其他地方不可访问.C++具有"受保护"属性用于此目的,但据我所知,Fortran 2003中的"protected"属性具有不同的含义(它使得A%x在任何地方都可访问并且仅保护其值,这在课堂外不能更改).
我试图将一个interfaced过程定义为Fortran type定义中的类型绑定过程,但它似乎无法正常工作.考虑以下模块:
module example_module
implicit none
private
interface add_them
module procedure add_them_integer,add_them_real
end interface add_them
type, public :: foo
integer, private :: a=1,b=2
real, private :: c=4.,d=5.
contains
procedure, public :: add => add_them
end type foo
contains
subroutine add_them_integer(self,x)
class(foo), intent(in) :: self
integer, intent(in) :: x
print *,self%a+self%b+x
end subroutine add_them_integer
subroutine add_them_real(self,x)
class(foo), intent(in) :: self
real, intent(in) :: x
print *,self%c+self%d+x
end subroutine add_them_real
end module example_module
Run Code Online (Sandbox Code Playgroud)
以及使用该模块的相应程序:
program example
use example_module
implicit …Run Code Online (Sandbox Code Playgroud)