Using an object in unrelated class
I have the following situation:
In project A, an object (say Obj1 of class A1) instantiates Obj2 of class A2.
Then, from Obj1, by many code paths, an object Obj3 (of class A3) can be instantiated. The A3 class is in another project.
The stack trace from Obj1's main method to instantiating an object of class A3 is 20 calls deep, and there are at least 100 places in the code where the function that instantiates the A3 class is called.
Now I want to add a non-static method to class A2 (say test()), and be able to call Obj2.test() (not A2::test()) from all instances of class A3.
How could I go about this in the most reasonable way?
Edit: some code:
class A2
{
//...
A2(string,string,...);
开发者_如何学Go double test();
};
A2::A2(string,string,...)
{
//...
}
double A2::test()
{
//return 4.2; //in reality it's more complicated
}
class A1{
//...
A2* Obj2;
};
A1::A1()
{
Obj2 = new A2(string,string,...);
}
A1:run()
{
//here there are many possible code paths (switches instantiating objects of other classes)
//but all end up as:
A3* Obj3 = new A3();
Obj3->test_wrapper();
}
class A3{
//this is defined in another project, and I'd prefer that project doesn't reference A2 since A2 links against a couple of libraries...
static double A3::test_wrapper();
};
static double A3::test_wrapper()
{
//if I had Obj2 here, I'd do:
return Obj2.test();
//but I don't...
}
There's not enough information here to answer.
- Does A1 have an A2 or A3 member? Does A2 or A3 have an A1 member?
- What are the arguments to the instantiation of A2 or A3?
If A3 wants to call Obj2.test(), then either
- A3 needs a member of type A2
- A3 needs a member of type X that has a member of type A2 -- probably should forward the call through X, though
- The method in A3 that needs to call test needs to take an A2 argument
- The method can take an argument X that has an A2 member (again, forward through X).
It's probably not a good idea to start using some global thing to stuff an A2 into and get back from A3.
If there is only one method of A3 that needs to call A2, then can A2 be a member of that method? Do all callers have an A2 (or are they able to get one?).
Can the functionality of A2's test() go somewhere else?
精彩评论