class A {
 void methodToCall() {};
}

class B {
 B() {
   subscribeToEvent();
 }
 void eventHandler(Event* E) {
   call A::methodToCall()
 }
}

class C : public A, public B{
}  

This may seem like a rare situation so let me explain what I'm trying to do.

I have alot of classes that are like class A. These are generated by another framework so I do not have control over how they are generated.

For every class A I have one or more class C's that inherit a class like A.

I have developed the need to call A::MethodToCall() when eventHandler() is called. My goal is not to have to subscribe and provide an eventhadler method in all of my classes like class C.

I would much rather create a one class B that all my class C's can simply inherit.

My problem is I do not know how to make the call to class A from class B.

If there is a better way of doing this I'm open to it.

有帮助吗?

解决方案

Your code doesn't match your description (in the code B does not inherit from A, whereas in your description it does), but I think what you're saying is "I have a large number of classes like A, and a large number of classes that inherit from classes like A (C in your example), and there's a bunch of common stuff in those subclasses I'd like to factor out (into B in your example), but it includes stuff that depends on the specific A (calling an A method in your example) and it defeats the whole point to have to make many B's (one for each A) mostly all alike."

One thing you could use is the 'template class inheriting from argument' trick to define large numbers of B variants as a single template class:

template<class A> B : public A {
    void eventHandler(Event* E) {
       call methodToCall(); 
    }
}

class C1 : public B<A1> {
     ... whatever

class C2 : public B<A2> { ...

If you have certain A classes that need slightly different stuff in B, you can also specialize the B template for those classes.

其他提示

This code

class A {
 void methodToCall() {};
}

Should be

class A {
 static void methodToCall() {};
}

For this to work:

 void eventHandler(Event* E) {
   A::methodToCall()
 }

Because you do not have an object of type A and 'B' knows nothing of A - so only static methods will be available.

Alternatively do this

class B : public A ....
class C: public B

Then the static is not required as B is inheriting A.

The choice is yours.

You could write a wrapper class, which is a subclass of A and B. The subclass, call it D, would then know of both A and B, so when event occurs, D is responsible for handling it and calling A. Then you can have your class C just inherit class D.

EDIT: I think I misinterpreted your question here. If B inherits A, then B can call a function in A directly (as long as A's method is not private. If it were, you wouldn't be able to call it anyways).

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top