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;
}
相关推荐
罗政2 小时前
[附源码]超简洁个人博客网站搭建+SpringBoot+Vue前后端分离
vue.js·spring boot·后端
迷迭所归处3 小时前
C++ —— 关于vector
开发语言·c++·算法
CV工程师小林3 小时前
【算法】BFS 系列之边权为 1 的最短路问题
数据结构·c++·算法·leetcode·宽度优先
拾光师4 小时前
spring获取当前request
java·后端·spring
white__ice4 小时前
2024.9.19
c++
天玑y4 小时前
算法设计与分析(背包问题
c++·经验分享·笔记·学习·算法·leetcode·蓝桥杯
姜太公钓鲸2334 小时前
c++ static(详解)
开发语言·c++
菜菜想进步4 小时前
内存管理(C++版)
c语言·开发语言·c++
Joker100855 小时前
C++初阶学习——探索STL奥秘——模拟实现list类
c++
科研小白_d.s5 小时前
vscode配置c/c++环境
c语言·c++·vscode