📜  C++中的早期绑定和晚期绑定

📅  最后修改于: 2021-05-30 04:36:31             🧑  作者: Mango

绑定是指将标识符(例如变量和性能名称)转换为地址的过程。对每个变量和函数进行绑定。对于函数,这意味着将编译器的调用与正确的函数定义进行匹配。它发生在编译时或运行时。

cpp绑定

早期绑定(编译时时间多态性)顾名思义,编译器(或链接器)直接将地址与函数调用关联。它用机器语言指令代替该调用,该指令告诉大型机跳转到该函数的地址。

默认情况下,早期绑定发生在C++中。后期绑定(在下面讨论)是通过virtual关键字实现的)

// CPP Program to illustrate early binding.
// Any normal function call (without virtual)
// is binded early. Here we have taken base
// and derived class example so that readers
// can easily compare and see difference in
// outputs.
#include
using namespace std;
    
class Base
{
public:
    void show() { cout<<" In Base \n"; }
};
    
class Derived: public Base
{
public:
    void show() { cout<<"In Derived \n"; }
};
    
int main(void)
{
    Base *bp = new Derived;
  
    // The function call decided at 
    // compile time (compiler sees type
    // of pointer and calls base class
    // function.
    bp->show();  
  
    return 0;
}

输出:

In Base

Late Binding :(运行时多态)在这种情况下,编译器将添加代码,以在运行时标识对象的类型,然后将调用与正确的函数定义进行匹配(有关详细信息,请参见此内容)。这可以通过声明一个虚函数来实现。

// CPP Program to illustrate late binding
#include
using namespace std;
    
class Base
{
public:
    virtual void show() { cout<<" In Base \n"; }
};
    
class Derived: public Base
{
public:
    void show() { cout<<"In Derived \n"; }
};
    
int main(void)
{
    Base *bp = new Derived;
    bp->show();  // RUN-TIME POLYMORPHISM
    return 0;
}

输出:

In Derived
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”