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;
}
相关推荐
YuforiaCode3 小时前
第十六届蓝桥杯 2025 C/C++B组第一轮省赛 全部题解(未完结)
c语言·c++·蓝桥杯
lsnm3 小时前
【LINUX操作系统】线程操作
linux·jvm·c++·ubuntu·centos·gnu
zhengtianzuo3 小时前
043-代码味道-循环依赖
c++
CoderCodingNo3 小时前
【GESP】C++三级练习 luogu-B2118 验证子串
开发语言·c++
运维@小兵4 小时前
SpringBoot获取用户信息常见问题(密码屏蔽、驼峰命名和下划线命名的自动转换)
java·spring boot·后端
hu_yuchen5 小时前
C++:Lambda表达式
开发语言·c++·算法
一只鱼^_5 小时前
牛客周赛 Round 91
数据结构·c++·算法·数学建模·面试·贪心算法·动态规划
问道飞鱼6 小时前
【springboot知识】配置方式实现SpringCloudGateway相关功能
java·spring boot·后端·gateway
樽酒ﻬق6 小时前
打造美观 API 文档:Spring Boot + Swagger 实战指南
java·spring boot·后端
2401_858286116 小时前
CC52.【C++ Cont】滑动窗口
开发语言·数据结构·c++·算法·leetcode·滑动窗口