oop - 分配对象引用而不是对象

标签 oop julia

我在 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.sonson = 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/

相关文章:

dataframe - 在 Julia Jupyter Notebook 中以 Nice 格式显示整个 DataFrame

c++ - 如何使大多数编辑器可折叠类实现的代码?

oop - 从全局状态转移到依赖注入(inject)等模式的好机制是什么?

python - "unqualified on right hand side"在 OOP(Python)中意味着什么?

julia - Searchlight.jl 支持哪些数据类型?

julia - 如何在 Julia 中有效地初始化巨大的稀疏数组?

dataframe - Julia DataFrame 行数据类型已更改?

Julia 相当于 Python 的 "help()"

ruby - 返回 ruby 中的对象

java - mock 单例类