静态绑定与动态绑定
- 静态绑定:编译阶段完成。成员函数重载以及派生类对基类的重载就是静态绑定。发生调用时由参数类型决定,与指向对像无关。
class static_binding
{
public:
void play()
{
printf("static_binding play()\n");
}
};
class static_binding_child : public static_binding
{
public:
void play()
{
printf("static_binding_child play()\n");
}
};
void show(static_binding &sb)
{
sb.play();
}
int main(int argc, char *argv[])
{
static_binding sb;
static_binding_child sbc;
show(sb);
show(sbc);
return 0;
}
- 动态绑定:运行时完成。能动态地根据指针或引用对象的实际类型来选择调用的函数。通常用虚函数实现。
class dynamic_binding
{
public:
virtual void play()
{
printf("dynamic_binding play()\n");
}
};
class dynamic_binding_child : public dynamic_binding
{
public:
void play()
{
printf("dynamic_binding_child play()\n");
}
};
void show(dynamic_binding &db)
{
db.play();
}
int main(int argc, char *argv[])
{
dynamic_binding db;
dynamic_binding_child dbc;
show(db);
show(dbc);
dynamic_binding *pdb = &dbc;
show(*pdb);
dynamic_binding_child *pdbc = (dynamic_binding_child *)&db;
show(*pdbc);
return 0;
}
|