球坐标和直角坐标能不能继承于同一个父类的问题
本帖最后由 lookbook 于 2019-1-13 21:08 编辑2D球坐标(r,phi)
2D直角坐标(x,y)
-----------------------
3D球坐标(r,theta,phi)
3D直角坐标(x,y,z)
-----------------------
球坐标和直角坐标只不过是描述同一个事物的不同描述方法,有一些物理量是不会随坐标变换和变化的,比如说长度,
那么是否可以使得:2D球坐标 和 2D直角坐标,共同继承于一个相同的父类?
另外:
3D球坐标继承于2D球坐标
3D直角坐标继承于2D直角坐标
这里遇到一个 “=” 号的问题,
2D球=3D球,则x,y被赋值,
反之,x,y被赋值但z等于0,同理直角坐标。
但这之后,以下思路会出现问题:
如何再设计一个“=”,让 球坐标=直角坐标,或者 直角坐标=球坐标时,
直接进行转化。
module Point_m
implicit none
type,abstract:: Point
end type
end module
module Point2D_m
use Point_m
implicit none
type,extends(Point):: Point2D
real x, y
end type
end module
module Point3D_m
use Point2D_m
implicit none
type,extends(Point2D):: Point3D
real z
end type
end module
module Point2D_sph_m
use Point_m
implicit none
type,extends(Point):: Point2D_sph
real r, phi
end type
end module
module Point3D_sph_m
use Point2D_sph_m
use Point3D_m
implicit none
type,extends(Point2D_sph):: Point3D_sph
real theta
contains
procedure XYZ2Sph, sph
generic:: assignment(=) => XYZ2Sph, sph
end type
contains
subroutine XYZ2Sph(this,other)
implicit none
class(Point3D_sph),intent(inout) :: this
class(Point2D),intent(in) :: other
select type(other)
class is(Point2D)
this%r = 1
this%phi = 2
this%theta = 0
class is(Point3D)
this%r = 1
this%phi = 2
this%theta = 3
end select
end subroutine XYZ2Sph
subroutine Sph(this,other)
implicit none
class(Point3D_sph),intent(inout) :: this
class(Point2D_sph),intent(in) :: other
select type(other)
class is(Point2D_sph)
this%r = 5
this%phi = 6
this%theta = 0
class is(Point3D_sph)
this%r = 5
this%phi = 6
this%theta = 7
end select
end subroutine sph
end module
program test
use Point3D_m
use Point3D_sph_m
type(point2d) a
type(point3d) b
type(point2d_sph) c
type(point3d_sph) d
d = a
print*,d
d = b
print*,d
d = c
print*,d
d = d
print*,d
pause
end
这些都可以做,但是这个父类设计没啥意思啊 liudy02 发表于 2019-1-14 10:11
这些都可以做,但是这个父类设计没啥意思啊
单独实现:
情况1:
2d直角=3d直角 & 3d直角=2d直角
2d球=3d球 & 3d球=2d球
或
情况2:
球=直角
直角=球
1和2各自实现都可以,但一齐实现对我而言有点难度。
大兄弟怎么做到的? lookbook 发表于 2019-1-15 13:47
单独实现:
情况1:
2d直角=3d直角 & 3d直角=2d直角
没明白你的难处在哪里?既然都可以实现赋值,为什么会有问题
另外其实也不是很明白你这这么奇怪的需求是从哪里来的…… liudy02 发表于 2019-1-15 15:00
没明白你的难处在哪里?既然都可以实现赋值,为什么会有问题
另外其实也不是很明白你这这么奇怪的需求是 ...
如果同时assignment(=)=> balbalbal....
那这个等号的重载将会遇到问题。 lookbook 发表于 2019-1-15 23:23
如果同时assignment(=)=> balbalbal....
那这个等号的重载将会遇到问题。
每一个等号重载只在被赋值的(子)类中定义和实现
页:
[1]