问题描述
考虑以下代码
module class_type
implicit none
class(*), pointer :: fnzo => null()
type, abstract :: gen
real :: ss
integer :: sdsd
class(gen), pointer :: next =>null()
end type
type, extends(gen) :: final1
real :: ss1
end type final1
type, extends(gen) :: final2
real :: x1(10)
end type
end module class_type
program test_class
use class_type
implicit none
class(gen), pointer :: test
type(final1) :: test1
allocate(test, source = test1)
print*, test% ss1
end program
我正在尝试制定一个链接列表,其中每个下一个元素都继承 final1
或 final2
.目前,仅测试简单的案例,我不明白为什么我无法访问 test%ss1
.任何人都可以帮助
I am trying to work out a a linked - list where each next element either inherits final1
or final2
. Currently, just testing simple cases and I don't understand why I cannot access test%ss1
. Anyone to help
推荐答案
至于为什么我们不能访问 test%ss1
",下面的代码对于考虑原因可能很有用.在这段代码中,我得到了用户输入( inp
),并确定 ptr
指向类型为 test1
还是 test2 .如果
ptr
指向 test2
变量,则访问 ptr%ss1
显然是没有意义的,因此编译器需要防止此类错误访问.我认为这就是为什么除非提供 select type
(用于内存中的实际数据)的原因,否则编译器仅允许访问 gen
(=声明的类型)的组件.
As for "why we cannot access
test% ss1
", the following code might be useful for considering the reason. In this code, I get a user input (inp
) and determine whether ptr
points to variables of type test1
or test2
. If ptr
points to a variable of test2
, accessing ptr% ss1
is clearly meaningless, so the compiler needs to guard against such an incorrect access. I think that is why the compiler allows only the access of components of gen
(= declared type) unless select type
(for actual data in memory) is provided.
program test_class
use class_type
implicit none
class(gen), pointer :: ptr !! parent type
type(final1), target :: test1 !! child type
type(final2), target :: test2 !! child type
integer :: inp
print *, "input some integer"
read *, inp
if ( inp == 1 ) ptr => test1
if ( inp == 2 ) ptr => test2
print*, "ptr% ss = ", ptr% ss !! OK
! print*, "ptr% ss1 = ", ptr% ss1 !! error (Line1)
select type ( ptr )
type is ( final1 ); print*, "ss1 = ", ptr% ss1 !! OK
type is ( final2 ); print*, "x1 = ", ptr% x1 !! OK
endselect
end program
如果Line1未被注释,则给出错误(使用gfortran-8)
If the Line1 is uncommented, it gives an error (with gfortran-8)
print*, "ptr% ss1 = ", ptr% ss1 !! error
1
Error: 'ss1' at (1) is not a member of the 'gen' structure; did you mean 'ss'?
我猜情况与其他(静态类型的)语言相似.例如,当我们访问
ptr-> b
时,C ++中的以下代码给出了错误.
I guess the situation is similar to other (statically typed) languages. For example, the following code in C++ gives an error when we access
ptr->b
.
#include <iostream>
using namespace std;
struct A {
int a = 1;
};
struct B : A {
int b = 100;
};
int main() {
A *ptr;
ptr = new B;
cout << ptr->a << endl; // 1
// cout << ptr->b << endl; // error: 'struct A' has no member named 'b'
delete ptr;
}
这篇关于在Fortran中访问子声明类型的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!