一、重载
- struct mystru
- {
- const char *name;
- double d;
- int number;
- };
- void myfunc(struct mystru ms)
- {
- printf("%s, %lf, %d\n", ms.name, ms.d, ms.number);
- }
- //使用
- #define func(...) myfunc((struct mystru) { __VA_ARGS__})
- func("name",2.2);
1.用可变fun(...)传入可变形参。
2.将{__VA_ARGS__}强制类型转换为struct mystru 。__VA_ARGS__ 为可变参宏
3.调用myfunc
二、运行时绑定(一个简单的方法)
用父类解释子类申请的内存的时候,用相同的函数指针名字,访问同一片内存保存的指针的值,伪造出运行时绑定。
1.在子类和父类中分别定义相同名字的函数指针,就可以用父类访问到子类函数。
struct A{
void (*foo)();
};
struct B{
void (*foo)();
};
void A_foo()
{
printf("this is A!\n");
}
void B_foo()
{
printf("this is B!\n");
}
void A_construct(struct A *p)
{
p->foo =A_foo;
}
void B_construct(struct B *p)
{
p->foo = B_foo;
}
int main(void)
{
printf("Hello World!\n");
struct A *a = (struct A *)malloc(sizeof(struct A));
struct B *b = (struct B *)malloc(sizeof(struct B));
A_construct(a);
B_construct(b);
//a->foo();
//b->foo();
a =(struct A*) b;
a->foo();
return 0;
}
2.如果想访问成员变量还需要将this指针保存起来,
用父类对象访问子类的成员变量时,还需要将自身的指针传入当做参数,再访问成员变量。//没什么意义啊