从其他类实例访问类实例
我有 4 个类:A、B、C 和 D。A
实际上是一个主类,并且具有 B、C 和 D 的实例:
class A() {
var B_class : B = new B()
var C_class : C = new C()
var D_class : D = new D()
}
D 类具有使用 C 类方法的方法。但这些方法需要知道C类的状态。
所以我的理解是,在构造 D 类时,我需要将 C 类作为参数传递,如下所示:
class A() {
var B_class : B = new B()
var C_class : C = new C()
var D_class : D = new D(C_class)
}
但另一个问题是 C_class 还需要使用 D_class 中的方法来更改 D_class 的状态。如果一切都在一个类中,那就很容易了。
当然,我可以只拥有接受特定类的方法,但必须有更好的方法。我确信我在设计中忽略了一些基本的东西。
I have 4 classes: A, B, C and D.
A is really a main class, and has instances of B, C and D:
class A() {
var B_class : B = new B()
var C_class : C = new C()
var D_class : D = new D()
}
The D class has methods that use methods from C class. But these methods need to know the state of C class.
So my understanding is I would need to pass C class in as a parameter when constructing D class like so:
class A() {
var B_class : B = new B()
var C_class : C = new C()
var D_class : D = new D(C_class)
}
But the other issue is the fact that C_class also needs to use methods from D_class that change the state of D_class. If everything was in one class it'd be easy.
Sure, I could just have methods that take specific classes, but there must be a better way. I'm confident I've overlooked something basic in my design.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不确定这是否适用于您的 OO 语言,但是您可以轻松地让
C_class
包含对D
的引用和D_class
的引用到C
:关键是可以有不完整类型的指针和引用。由于您不需要实际的相互嵌套成员(无论如何这都没有意义),而只需要引用,因此您可以轻松地拥有这样的循环引用。
I'm not sure if this applies to your OO language, but in you can easily have
C_class
contain a reference toD
andD_class
a reference toC
:The key is that it's possible to have pointers and references to incomplete types. Since you don't need actual mutually nested members (which wouldn't make sense anyway), but only references, you can easily have circular references like this.
要么你可以给C添加一个SetD方法,要么你需要C构造D,D构造C,这是不可能的。如果不是显式 SetD,则将 D 作为参数传递给需要 D 方法的 C 方法可能会成功。
Either you can add a SetD method to C, or you need C to construct D and D to construct C, which is impossible to make work. If not an explicit SetD, then passing D as an argument to the methods of C which need D's methods might potentially work out.