Fortran 2008 - переменная массива в классе - PullRequest
0 голосов
/ 03 июня 2018

У меня есть следующий класс, где мне нужно хранить объекты типа neuron_t и connection_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_t расширяет тип neuron_t, поэтому все должно быть в порядке.

EDIT:

Оба класса 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

1 Ответ

0 голосов
/ 03 июня 2018

Нельзя просто назначить полиморфную переменную в присваивании (=).Это можно сделать только для выделяемых переменных, и элемент массива не является выделяемой переменной, даже если он является частью выделяемого массива.Помните, все элементы массива должны иметь один и тот же динамический тип .

Поэтому, если вы хотите, чтобы разные элементы 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) будет недостаточно?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...