2

我有一个以下类,我需要在其中存储类型neuron_tconnection_t.

!> Class representing a general network
type :: net_t
    private

    character(:), allocatable                 :: net_type              !< Type of the net
    integer(kind=integer_4neuro)              :: num_of_neurons        !< Number of neurons in the net
    character(:), allocatable                 :: training_method       !< Used training method

    class(neuron_t), allocatable              :: neuron_arr(:)         !< Array containing all neurons
    integer(kind=integer_4neuro), allocatable :: input_neuron_arr(:)   !< Array of input neuron indices
    integer(kind=integer_4neuro), allocatable :: output_neuron_arr(:)  !< Array of output neuron indices
    class(connection_t), allocatable          :: connection_arr(:)     !< Array of all connections

contains
    !> Prints information about the network to the standard output.
    procedure :: print_info => print_info_impl

    !> Saves the network instance to the Fortran binary file
    procedure :: save_net_bin => save_net_bin_impl

end type net_t

interface net_t
    !> Constructor of net_t class
    !! Loads complete info about network from file
    !! @param[in] filepath Path to the file with network configuration
    !! @return Returns pointer to the new instance of the class net_t
    module procedure :: new_net_1
end interface net_t

我试图像这样初始化数组

    allocate(new_obj)

    ! Init object
    do i=1,5
        new_obj%neuron_arr(i) =  mock_neuron_t()
    end do

但我收到以下错误:

         new_obj%neuron_arr(i) =  mock_neuron_t()
        1
Error: Nonallocatable variable must not be polymorphic in intrinsic assignment at (1) - check that there is a matching specific subroutine for '=' operator

你知道吗,我做错了什么?mock_neuron_textends type neuron_t,所以应该没问题。

编辑:

neuron_t和类都是connection_t抽象的,所以添加后我现在收到以下错误allocate(new_obj%neuron_arr)

     allocate(new_obj%neuron_arr)
             1
Error: Allocating new_obj of ABSTRACT base type at (1) requires a type-spec or source-expr

         new_obj%neuron_arr(i) =  mock_neuron_t()
        1
Error: Nonallocatable variable must not be polymorphic in intrinsic assignment at (1) - check that there is a matching specific subroutine for '=' operator
4

1 回答 1

3

您不能只在内部赋值 ( =) 中赋值给多态变量。您只能对可分配变量执行此操作,并且数组元素不是可分配变量,即使它是可分配数组的一部分。请记住,所有数组元素必须具有相同的动态类型

因此,如果您想让不同的元素neuron_arr(:)具有不同的类型,那是不允许的。

但是您可以将数组分配给某个单一类型并使用类型select type保护。

allocate(new_obj)

allocate(new_obj%neuron_arr)  !this allocates it to the declared type neuron_t!

! Init object
select type(a => new_obj%aneuron_arr)
  type is(neuron_t)
    do i=1,5
      a(i) =  mock_neuron_t()
    end do
end select

但是,如果你总是有一种固定类型,那还type(neuron_t)不够吗?

于 2018-06-03T20:05:50.583 回答