Function overloading and inline functions
Function overloading
-
C++ can use the function of the same name [overloaded function] to implement multiple different functions with similar functions.
-
Function name overload:
The function name is the same,
However, the parameters (formal parameters) of the function are never the same:
-
Different number of parameters
-
Or the number of parameters is the same, but the types of the parameters are different
Only the return type is different, it cannot constitute a function overload
Only the formal parameter variable name is different, and it cannot constitute a function overload.
Note: C language does not support function overloading
-
-
Example:
#include <iostream>
using namespace std;
int add(int a, int b) {
return a + b;
}
float add(float a, float b) {
return a + b;
}
int main(void) {
int a1 = 1, b1 = 2;
float a2 = 1.0, b2 = 0.2;
cout << add(a1, b1) << endl; //调用int add(int a, int b)
cout << add(a2, b2) << endl; //调用float add(float a, float b)
return 0;
}
Function stack space
-
To avoid stack space overflow.
When a function is called, a memory area is allocated for this function in the stack space,
This memory area is dedicated to this function.
This memory area is called "stack frame".
#include <iostream>
#include <Windows.h>
void test(void) {
//运行时将因为栈帧空间溢出,而崩溃
char buff[2000000];
std::cout << (int)buff[sizeof(buff) - 1] <<std::endl;
}
int main(void) {
test();
system("pause");
return 0;
}
Inline function
-
The role of the function:
避免重复制造轮子。 (避免重复多次写相同的代码)
Disadvantages of functions:
每调用一次函数,就会为这个函数分配一个“栈”, 在计算机底层做很多准备工作(保护原来的执行环境,切换到新的执行环境) 有一定的“时间开销”
solution:
使用内联函数
Inline function:
当编译器在编译时, 如果遇到内联函数, 就会直接将整个函数体的代码插入”调用处”, 就相当于内联函数的函数体, 在调用处被重写了一次。 以避免函数调用的开销, 获得更快的时间。
Disadvantages of inline functions:
使调用内联函数的程序,变得“臃肿”,消耗调用函数的“栈”空间。
Usage of inline functions:
inline int add(int a, int b) { return a + b; }
Use cases of inline functions:
1)内联函数中的代码应该只是很简单、执行很快的几条语句。 2)这个函数的使用频度非常高,比如在一个循环中被千万次地使用。 数的定义(即整个数体),而不能只出现内联函数的声明。