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;
}
相关推荐
千谦阙听5 分钟前
C++类和对象(中):默认成员函数、构造与析构、拷贝构造、运算符重载
开发语言·c++·学习
骇客野人11 分钟前
SpringBoot电商系统用户注册、登录、留存及数据埋点设计与落地实施方案
java·spring boot·后端
weixin_3077791331 分钟前
一维无粘 Burgers 方程的激波形成问题:MacCormack 格式求解
c++·算法·matlab
HugoStudio_SWAN1 小时前
洛谷 B4500 / B4449 / B3843 凯撒密码、密码强度与密码合规——加密与安全的三道门
c++·学习·程序人生·算法·安全
雾里看山2 小时前
源码目录、构建目录与 out-of-source build
c++·软件构建·cmake
IT_陈寒3 小时前
React的状态更新坑得我差点加班到天亮
前端·人工智能·后端
渡我白衣3 小时前
并查集:基础认识与模拟实现
android·java·javascript·数据结构·c++·算法·并查集
如意猴4 小时前
【C++】001--C++入门(1)
开发语言·c++
hetao17338374 小时前
2026-09-01~09-04 hetao1733837 的刷题记录
c++·算法
码事漫谈4 小时前
一天搭出 80% 的 Agent,然后卡在 95% 到死
后端