我在 Julia 中遇到了绑定(bind)问题
尝试执行此操作时:
type Chain
value :: Int
son :: Chain
#Make the last link in the chain point to itself
#so as to spare us from the julia workaround for nulls
Chain(value::Int) = (chain = new(); chain.value = value; chain.son = chain; chain)
end
#Create three separate nodes
c=Chain(5)
d=Chain(2)
e=Chain(1)
#Link an object to another and then modify the linked object
c.son = d
son = d.son
son = e
c
我想更改父级中儿子的链接,但仅当我这样做时才有效:
c.son = d
d.son = e
c
这在递归函数中产生了一个问题,如果将一个对象传递给链接到另一个对象的函数并在函数体中更改它,那么链接不会更改,只会更改对象本身。
我试过使用 julia 函数
pointer_from_objref
,但这用于处理 c 函数和 unsafe_store!
的分配没用。我将如何创建一个变量,当分配给它时也会更改我引用的链接?
最佳答案
如果我了解你的属性(property),你可以声明son
作为 Array
=> son::Array{Chain,1}
为达到这个。
type Chain
value::Int
son::Array{Chain,1}
Chain(value::Int) = (chain = new(); chain.value = value; chain.son = [chain]; chain)
end
julia> c=Chain(5)
Chain(5,[Chain(#= circular reference =#)])
julia> d=Chain(2)
Chain(2,[Chain(#= circular reference =#)])
julia> e=Chain(1)
Chain(1,[Chain(#= circular reference =#)])
julia> c.son = [d]
1-element Array{Chain,1}:
Chain(2,[Chain(#= circular reference =#)])
julia> son = d.son
1-element Array{Chain,1}:
Chain(2,[Chain(#= circular reference =#)])
julia> son[:] = e
Chain(1,[Chain(#= circular reference =#)])
julia> c
Chain(5,[Chain(2,[Chain(1,[Chain(#= circular reference =#)])])])
这是因为通过运行
son = d.son
和 son = e
,您只需完全更改绑定(bind)。# NOT using array type
julia> son = d.son
Chain(2,Chain(#= circular reference =#))
julia> son = e
Chain(1,Chain(#= circular reference =#))
julia> son === d.son
false
# using array type
julia> son = d.son
1-element Array{Chain,1}:
Chain(2,[Chain(#= circular reference =#)])
julia> son[:] = e
Chain(1,[Chain(#= circular reference =#)])
julia> son === d.son
true
如果要保留链接,解决方法是使用数组类型并更改数组的内容而不是其绑定(bind)。 more details about bindings .
关于oop - 分配对象引用而不是对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32927633/