C ++中的早期绑定和晚期绑定
在本节中,我们将了解什么是早期绑定以及什么是C++中的后期绑定。绑定是指将标识符转换为地址的过程。对于每个变量和函数,都完成了绑定。对于函数,它将调用与编译器正确的函数定义匹配。绑定在编译时或运行时完成。
早期绑定
这是编译时多态。在这里,它直接将地址与函数调用关联。对于函数重载,这是早期绑定的一个示例。
示例
#include<iostream>
using namespace std;
class Base {
public:
void display() {
cout<<" In Base class" <<endl;
}
};
class Derived: public Base {
public:
void display() {
cout<<"In Derived class" << endl;
}
};
int main(void) {
Base *base_pointer = new Derived;
base_pointer->display();
return 0;
}输出结果
In Base class
后期绑定
这是运行时多态。在这种类型的绑定中,编译器添加了在运行时标识对象类型的代码,然后将该调用与正确的函数定义进行匹配。这是通过使用虚拟功能来实现的。
示例
#include<iostream>
using namespace std;
class Base {
public:
virtual void display() {
cout<<"In Base class" << endl;
}
};
class Derived: public Base {
public:
void display() {
cout<<"In Derived class" <<endl;
}
};
int main() {
Base *base_pointer = new Derived;
base_pointer->display();
return 0;
}输出结果
In Derived class