c++ 静态联编

文章作者:里海
来源网站:https://blog.csdn.net/WangPaiFeiXingYuan


简介:

        C++中的静态联编(Static Binding)是指在编译时期进行的联编方式,也称为早期联编或静态多态性(Static Polymorphism)。

        在静态联编中,函数的调用和绑定在编译时期就已经确定,也就是说,函数的调用和绑定是与对象类型无关的,编译器会根据函数的指针或引用类型来确定应该调用哪个函数。

        静态联编的优点是编译器可以提前发现一些类型错误,并且程序运行时的开销较小。但是静态联编也有缺点,它缺乏动态性,无法在运行时期动态地改变函数的调用关系,也无法实现多态性。

     

以下是一个静态联编的示例:

#include <iostream>  
using namespace std;  
  
class Base 
{  
public:  
    virtual void print() 
    {  
        cout << "This is Base class" << endl;  
    }  
};  
  
class Derived : public Base 
{  
public:  
    void print() 
    {  
        cout << "This is Derived class" << endl;  
    }  
};  
  
int main() 
{  
    Base *b;  
    Derived d;  
    b = &d;  
    b->print(); // 静态联编,调用Derived类的print函数  
    return 0;  
}

        在上面的示例中,通过Base类指针调用print函数时,由于指针类型是Base类,所以编译器会根据指针类型来调用Base类的print函数。但是,由于Derived类覆盖了Base类的print函数,所以实际上调用的是Derived类的print函数。这就是静态联编的实现方式。

猜你喜欢

转载自blog.csdn.net/WangPaiFeiXingYuan/article/details/131429059