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.
迟绑定发生在运行时,基于不同类型的对象。当一种语言实现迟绑定时,必须有某种机制确定对象的具体类型然后调用合适的成员函数。

引用一句Bruce Eckel的话:

不要犯傻,如果它不是晚邦定,它就不是多态。

很明显,迟绑定就是用来解决多态特性的。在 C++ 中,在基类的成员函数声明前加上关键字virtual即可让该函数成为虚函数,派生类中对此函数的不同实现都会继承这一修饰符,允许后续派生类覆盖,达到迟绑定的效果。 

示例:
class Animal
{
public:
	virtual void sleep()  //虚函数
	{
		cout << "Animal sleep!" << endl;
	}
 
	void breath()
	{
		cout << "Animal breath!" << endl;
	void sleep()   //函数重写,这里可以添加virtual,也可以不添加
	{
		cout << "Fish sleep!" << endl;
	}
	void breath()
	{
		cout << "Fish breath!" << endl;
	}
};
int main()
{
	Fish f;
	Animal* a = &f; //基类指针指向派生类
	a->breath();
	a->sleep();
	return 0;
}
// 结果:  Animal breath!
           Fish sleep!

已发布

分类

来自

标签:

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理