#include <iostream>
class A {
public:
A *self;
A(A*a):self(a) {}
virtual void fun() {
if (self) {
self->fun();
}
}
};
class B : public virtual A {
public:
B*self;
B(B* b):A(b),self(b) {}
virtual void fun1() {
if (self) {
self->fun1();
}
}
};
class E : public virtual A {
public:
E():A(this) {}
virtual void fun() {
std::cout << "fun:class E" << std::endl;
}
};
class F : virtual public E, virtual public B {
public:
F():A(this), B(this), E() {}
virtual void fun1() {
std::cout << "fun1:class F" << std::endl;
}
};
class C : virtual public B {
public:
C *self;
C(C *c): A(c), B(c), self(c) {}
virtual void fun2() {
if (self) {
self->fun2();
}
}
};
class G: virtual public C, virtual public F {
public:
G():A(this), B(this), C(this), F() {}
virtual void fun2() {
std::cout << "fun2:class G" << std::endl;
}
};
int main(int argc, char *argv[]) {
G g = G();
printf("1\n");
C *c = &g;
B *b = (B*)c;
A *a = (A*)b;
a->fun();
b->fun();
b->fun1();
c->fun();
c->fun1();
c->fun2();
printf("2\n");
A *a1 = &g;
B *b1 = &g;
C *c1 = &g;
a1->fun();
b1->fun();
b1->fun1();
c1->fun();
c1->fun1();
c1->fun2();
printf("3\n");
A ax(&g);
ax.fun();
B bx(&g);
bx.fun();
bx.fun1();
C cx(&g);
cx.fun();
cx.fun1();
cx.fun2();
printf("4\n");
A ax1(NULL);
ax1.fun();
B bx1(NULL);
bx1.fun();
bx1.fun1();
C cx1(NULL);
cx1.fun();
cx1.fun1();
cx1.fun2();
return 0;
}
打印结果:
$ ./example/test_multi_extend.exe
1
fun:class E
fun:class E
fun1:class F
fun:class E
fun1:class F
fun2:class G
2
fun:class E
fun:class E
fun1:class F
fun:class E
fun1:class F
fun2:class G
3
fun:class E
fun:class E
fun1:class F
fun:class E
fun1:class F
fun2:class G
4