Accessing class instances from other class instances
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开发者_StackOverflow中文版 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.
I'm not sure if this applies to your OO language, but in you can easily have C_class
contain a reference to D
and D_class
a reference to C
:
class C;
class D;
class C
{
D & otherD;
public:
C(D & d) : otherD(d) { }
};
class D
{
C & otherC;
public:
D(C & c) : otherC(c) { }
};
class A
{
C myC;
D myD;
public:
A() : myC(myD), myD(myC) { }
};
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.
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.
精彩评论