CLASS (Fortran 2003)
用途
CLASS 类型声明语句指定派生类型的对象的声明类型,类型参数和属性。 可以为对象赋予初始值。
语法
规则
TYPE 类型声明和 CLASS 类型声明的规则类似; 有关更多信息,请参阅 TYPE。
以下规则对于 CLASS 类型声明是唯一的:
- CLASS 类型说明符用于声明多态对象。 type_name 是多态对象的声明类型。
- 使用 CLASS(*) 说明符来声明无限多态对象。 无限多态实体没有被声明为具有类型,并且不会被视为具有与任何其他实体相同的声明类型,包括另一个无限多态实体。
- 使用 CLASS 关键字声明的实体必须是哑元自变量,或者具有 ALLOCATABLE 或 POINTER 属性。 此外,使用 CLASS 关键字声明的哑参数不得具有 value 属性。
示例
program sClass
type base
integer::i
end type
type,extends(base)::child
integer::j
end type
type(child),target::child1=child(4,6)
type(base), target::base1=base(7)
! declare an item that could contain any extensible derived type
! or intrinsic type
class(*),allocatable::anyThing
! declare basePtr as a polymorphic item with declared type base,
! could have run time type of base or child
class(base),pointer::basePtr
! set basePtr to point to an item of type child
basePtr=>child1
call printAny(basePtr)
! set basePtr to point to an item of type base
basePtr=>base1
call printAny(basePtr)
! allocate an integer item
allocate(anyThing, source=base1%i)
call printAny(anyThing)
contains
subroutine printAny(printItem)
! declare a dummy arg of unlimited polymorphic, can point
! to any extensible derived type or intrinsic type
class(*)::printItem
select type(item=>printItem)
type is (base)
print*,' base item is ',item
type is (child)
print*,' child item is ', item
type is (integer)
print*,' integer item is ',item
end select
end subroutine
end program
程序的输出为:
子项为 4 6
基本项为 7
整数项为 7
基本项为 7
整数项为 7
