如果您有一个对同一对象的引用数组,并尝试对其中的一个进行变异,那么您将得到该结果,例如,如果使用fill()
功能,以填补对象的数组,可能导致以下问题:
julia> s=Vector{Points}(3)
3-element Array{Points,1}:
#undef
#undef
#undef
julia> fill!(s,Points(NaN,NaN,NaN))
3-element Array{Points,1}:
Points(NaN,NaN,NaN)
Points(NaN,NaN,NaN)
Points(NaN,NaN,NaN)
julia> s[1].x=1
1.0
julia> s
3-element Array{Points,1}:
Points(1.0,NaN,NaN)
Points(1.0,NaN,NaN)
Points(1.0,NaN,NaN)
为了避免这种问题的使用数组,理解来填补它:
s=[Points(NaN,NaN,NaN) for i=1:3]
但是我从您的示例代码看到的是:
Points
数据类型没有自定义constructor
并且此外,s
数组还没有初始化化的。
julia> s = Array(Points,1,4)
1x4 Array{points,2}:
#undef #undef #undef #undef
所以如果你尝试变异元素上,你会得到一个错误:
最小的变化
julia> s[1].x
ERROR: UndefRefError: access to undefined reference
in getindex at array.jl:282
一个解决方案是使用Points
默认构造函数是这样的:
s[1]=Points(NaN,NaN,NaN)
后您将能够变异s
,s[1].x=4.28
其次具有Points
类型的zero
,应添加zero(::Points)
方法:
julia> import Base.zero
julia> zero(::Points)=Points(0,0,0)
zero (generic function with 14 methods)
julia> zero(Points(1,2,3))
Points(0.0,0.0,0.0)
提示:使用1XN阵列来处理N个元素的Array
是不是最好的选择,Refer,使用Vector{Type}(N)
代替。