今天看到一篇帖子关于虚函数的问题,原以为自己已经对c++虚函数,多态了解的不错了,但是,还是发现有一些模糊点,所以,又回头重新总结了一番。
有了不小的收获,下面,就和大家一起来分享一下,也希望对一些朋友起到一定的帮助。
首先先梳理一下概念,以前似乎对概念不是很重视,其实不然,真正对一个东西的定义了解了很透,才能去深入挖掘这个东西的内涵。
好,首先,什么是绑定?( what`s the definition of binding? )
c++编程思想上有说到:
Connecting a function call to a function body is called binding.(将函数体和函数调用关联起来,就叫绑定)
然后,那么什么是早绑定?(Early binding)
When binding is performed before the program is run (by the compiler and linker), it' s called early binding
在程序运行之前(也就是编译和链接时),执行的绑定是早绑定。
然后,什么是迟绑定?(late binding)
late binding, which means the binding occurs at runtime, based on the type of the object.
When a language implements late binding, there must be some mechanism to determine the
type of the object at runtime and call the appropriate member function.
迟绑定发生在运行时,基于不同类型的对象。当一种语言实现迟绑定时,必须有某种机制确定对象的具体类型然后调用合适的成员函数。
好,下面不多啰嗦,上实例:(环境:XP3 + VS2005,)
下面的注释部分是调试时,监视窗口的结果
#include <iostream>
using namespace std;
class Base
{
public:
virtual void sleep() { cout << "Base::sleep()" << endl;}
};
//两个派生类Derive和Derive1
class Derive : public Base
{
public:
void sleep() { cout << "Derive::sleep()" << endl; }
};
class Derive1 : public Base
{
public:
void sleep() { cout << "Derive1::sleep()" << endl; }
};
int main()
{
Base b;