C++ 函数重载 默认参数 内联函数

2020-12-15  本文已影响0人  hank009

函数重载 (overload

规则

注意

int sum(int v1, int v2) {
    return v1 + v2;
}
int sum(int v1, int v2, int v3) {
    return v1 + v2 + v3;
}

void func(int v1, double v2) {
    cout << "func(int v1, double v2)" << endl;
}
void func(double v1, int v2) {
    cout << "func(double v1, int v2)" << endl;
}

默认参数

C++ 允许函数设置默认参数,在调用时可以根据情况省略实惨。

int age = 28;
void test(){
    cout << "test()" << endl;
}

void display(int a = 11,int b = 22, int c = age, void (*func)() = test){
    cout << "a is " << a << endl;
    cout << "b is " << b << endl;
    cout << "c is " << c << endl;
    func();
}

如果函数的实参经常时同一个值,可以考虑使用默认参数。


内联函数 (inline function)

内联函数:编译器会将内联函数调用展开为函数体代码。

OC、C++ 都有内联函数

内联函数可以解决 函数调用效率的问题:

什么地方适合用内联函数:
内联函数与宏
写了 inline 关键字,函数会不会内联,还与一下因素有关

上一篇下一篇

猜你喜欢

热点阅读