C++ 函数联编
# 一、联编
- 将源代码中的函数调用解释为执行特定的函数代码块被称为函数名联编(binding);
- 在 C 语言中,函数名联编非常简单,因为每个函数名都对应一个不同的函数,是一一对应的关系,不会有重名的函数;
- 在 C++ 预言中,函数名联编比较复杂,因为有函数重载和虚函数重写的功能,导致函数存在重名的情况,同一个函数名会同时对应多个函数;
# 二、静态联编
- 对于函数重载导致的重名函数,编译器可以同时查看函数名和函数参数来确定调用哪个同名函数,这个过程可以在编译期间完成,称为静态联编(static binding),又称为早期联编(earlybinding);
- 静态联编的效率更高,是 C++ 的默认选择;
#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;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 三、动态联编
- 对于在子类中对父类定义的虚函数重写导致的重名函数,使用哪一个同名函数不能在编译时确定的;
- 虚函数重载时,父类指针可以指向不同的子类对象,调用其定义的虚函数,最终实际会调用哪个虚函数是需要看父类指针是指向的哪个子类对象;
- 编译器不知道用户将选择哪种子类型的对象,编译器必须生成能够在程序运行时选择正确的虚方法的代码,这被称为动态联编(dynamicbinding),又称为晚期联编(late binding);
- 动态联编能够使程序在运行时进行决策,但是效率没有静态联编高;
- 仅将那些预期将被重新定义的函数声明为虚的,其他函数则不需要定义为虚函数,这样效率更高并且指出不要重新定义该函数;
#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;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
编辑 (opens new window)
上次更新: 2024/04/09, 20:00:06