Pointer to a class and function - problem
Firstly I'll show you few classes.
class A {
public:
B * something;
void callSomething(void) {
something->call();
}
};
class B {
public:
A * activeParent;
B(A * parent) {
activeParent = parent;
}
void call(void) {
activeParent->something = new C;
}
};
class C : public B {
public:
A * activeParent;
C(A * parent) {
activeParent = parent;
}
void call(void) {
// do something
}
};
A * object;
object = new A;
object->somethin开发者_如何学运维g = new B;
object->callSomething();
My app needs such a structure. When I do callSomething(), it calls B's call() but when B's call() changes the "something" to C, C's call() is triggered and I want to avoid that. How should I do?
Aside from the design decisions (e.g., cyclical dependencies)...
The only reason A's callSomething() method would call C's call() method from a pointer to B is if the call() method is virtual. To avoid calling C's call() method, here are a couple of options:
- Don't make the call() method virtual
- Rename one of B or C's call() method (preferred over the first option)
- Call B's call() method explicitly
To call B's call() method explicitly:
void callSomething(void) {
something->B::call();
}
精彩评论