多重继承+代理 好玩且有用

#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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值