C++ 函数联编

个人主页:二郎腿 (erlangtui.top)


一、联编

  • 将源代码中的函数调用解释为执行特定的函数代码块被称为函数名联编(binding);
  • 在 C 语言中,函数名联编非常简单,因为每个函数名都对应一个不同的函数,是一一对应的关系,不会有重名的函数
  • 在 C++ 预言中,函数名联编比较复杂,因为有函数重载和虚函数重写的功能,导致函数存在重名的情况,同一个函数名会同时对应多个函数

二、静态联编

  • 对于函数重载导致的重名函数,编译器可以同时查看函数名和函数参数来确定调用哪个同名函数,这个过程可以在编译期间完成,称为静态联编(static binding),又称为早期联编(earlybinding);
  • 静态联编的效率更高,是 C++ 的默认选择;
cpp 复制代码
#include <iostream>

// 重载函数,接受一个整数参数
void print(int num) {
    std::cout << "Integer number: " << num << std::endl;
}

// 重载函数,接受一个双精度浮点数参数
void print(double num) {
    std::cout << "Double number: " << num << std::endl;
}

int main() {
    int intNum = 10;
    double doubleNum = 3.14;

    // 调用print函数的重载版本
    print(intNum);     // 调用void print(int num)
    print(doubleNum);  // 调用void print(double num)

    return 0;
}

三、动态联编

  • 对于在子类中对父类定义的虚函数重写导致的重名函数,使用哪一个同名函数不能在编译时确定的;
  • 虚函数重载时,父类指针可以指向不同的子类对象,调用其定义的虚函数,最终实际会调用哪个虚函数是需要看父类指针是指向的哪个子类对象
  • 编译器不知道用户将选择哪种子类型的对象,编译器必须生成能够在程序运行时选择正确的虚方法的代码,这被称为动态联编(dynamicbinding),又称为晚期联编(late binding);
  • 动态联编能够使程序在运行时进行决策,但是效率没有静态联编高;
  • 仅将那些预期将被重新定义的函数声明为虚的,其他函数则不需要定义为虚函数,这样效率更高并且指出不要重新定义该函数;
cpp 复制代码
#include <iostream>
#include <string>

// 基类 Animal
class Animal {
public:
    virtual void makeSound() {
        std::cout << "Animal makes a sound" << std::endl;
    }
};

// 派生类 Dog
class Dog : public Animal {
public:
    void makeSound() override {
        std::cout << "Dog barks" << std::endl;
    }
};

// 派生类 Cat
class Cat : public Animal {
public:
    void makeSound() override {
        std::cout << "Cat meows" << std::endl;
    }
};

// 派生类 Bird
class Bird : public Animal {
public:
    void makeSound() override {
        std::cout << "Bird chirps" << std::endl;
    }
};

int main() {
    // 创建不同的子类对象
    Animal* animal1 = new Dog();
    Animal* animal2 = new Cat();
    Animal* animal3 = new Bird();

    // 调用虚函数,根据对象的实际类型执行相应的重写函数
    animal1->makeSound(); // 输出 "Dog barks"
    animal2->makeSound(); // 输出 "Cat meows"
    animal3->makeSound(); // 输出 "Bird chirps"

    delete animal1;
    delete animal2;
    delete animal3;

    return 0;
}
相关推荐
郑州光合科技余经理3 小时前
代驾系统架构拆解:订单链路、权限组织与私有化源码交付
开发语言·后端·算法·架构·系统架构·uni-app·php
hboot5 小时前
AI工程师第六课 - RAG检索增强生成
后端·langchain·llm
mldong6 小时前
jeeflow:98KB 的工作流引擎长什么样
后端
程序员cxuan8 小时前
速度太快了!本地可以跑 DeepSeek-V4-Flash 了
人工智能·后端·程序员
啊啊啊啊啊!!!!9 小时前
【c++】stack和queue的接口使用以及底层实现
开发语言·c++
阿祖zu9 小时前
芝士就是力量!开源私有化部署与 GitHub 双向同步的个人知识笔记 App
前端·后端·ios
不才不才不不才10 小时前
Spring 源码系列(16): doDispatch 全流程——一次请求的主干链路
java·后端·spring
IT_陈寒10 小时前
SpringBoot自动配置失效?这个隐藏配置坑了我一整晚
前端·人工智能·后端
搜狐技术产品小编202310 小时前
告别“黑盒”与误判:如何用“多智能体对抗辩论”重构内容安全审核系统
后端·多agent
DantyWei10 小时前
controller注册及调用时机
后端