我读到它是not possible有一个类的几个构造函数。所以,下面的代码将无法正常工作:有一个不同的公共构造函数,而不是私有的构造函数
class C
def initialize x
initialize x,0
end
# Some methods using the private constructor…
def foo
# …
bar = C.new 3,4
# …
end
private
def initialize x,y
@x = x
@y = y
end
end
我曾经想过用一个静态方法代替公共构造函数,但是这将防止其他类来扩展C
。我也考虑过使用私有后期初始化方法:
class C
def initialize x
post_init x,0
end
# Some methods using the private constructor…
def foo
# …
bar = C.new baz
bar.post_init 3,4
# …
end
private
def post_init x,y
@x = x
@y = y
end
end
但是在这里,post_init被调用两次,这不是一件好事。
有没有办法给一个公共的构造函数,而私下有一个更完整的方法来创建一个新的实例?如果不是,做类似的最好方法是什么?
我真的不明白你为什么想要这样做,但是你想出什么似乎符合你的目的,除了你的代码中的'post_init'是一个类方法,但是你从实例方法调用它,这是行不通的。 –
我对类方法犯了一个错误,它应该是一个实例方法。因此我更新了这个帖子。 – Codoscope
你有没有想过直接改变'@ y',你需要什么?它看起来像一个更常见和直接的方法 –