1. 程式人生 > >C++解析(6):函式引數的擴充套件

C++解析(6):函式引數的擴充套件

0.目錄

1.函式引數的預設值

2.函式預設引數的規則

3.函式佔位引數

4.小結

1.函式引數的預設值

  • C++可以在函式宣告時為引數提供一個預設值
  • 當函式呼叫時沒有提供引數的值,則使用預設值

引數的預設值必須在函式宣告中指定

執行以下程式:

#include <stdio.h>

int mul(int x = 0);

int main()
{
    printf("%d\n", mul());
    printf("%d\n", mul(-1));
    printf("%d\n", mul(2));
    
    return 0;
}

int mul(int x)
{
    return x * x;
}

執行結果如下:

[[email protected] Desktop]# g++ test.cpp
[[email protected] Desktop]# ./a.out 
0
1
4

以下這兩種情況都會報錯:

#include <stdio.h>

int mul(int x = 0);

int main()
{
    printf("%d\n", mul());
    printf("%d\n", mul(-1));
    printf("%d\n", mul(2));
    
    return 0;
}

int mul(int x = 5)
{
    return x * x;
}
#include <stdio.h>

int mul(int x);

int main()
{
    printf("%d\n", mul());
    printf("%d\n", mul(-1));
    printf("%d\n", mul(2));
    
    return 0;
}

int mul(int x = 5)
{
    return x * x;
}

2.函式預設引數的規則

  • 引數的預設值必須從右向左提供
  • 函式呼叫時使用了預設值,則後續引數必須使用預設值

3.函式佔位引數

在C++中可以為函式提供佔位引數

  • 佔位引數只有引數型別宣告
    ,而沒有引數名宣告
  • 一般情況下,在函式體內部無法使用佔位引數

函式佔位引數的意義:

  • 佔位引數與預設引數結合起來使用
  • 相容C語言程式中可能出現的不規範寫法

下面的兩種宣告方式等價嗎?
void func(); <——> void func(void);
回答:在C語言中是不等價的,在C++中是等價的!

將佔位引數與預設引數結合起來使用,用於將C語言程式移植到C++程式,並且沒有bug!

#include <stdio.h>

void func(int = 0, int = 0){}

int main()
{
    func();
    func(1, 2);
    
    return 0;
}

4.小結

  • C++中支援函式引數的預設值
  • 如果函式呼叫時沒有提供引數值,則使用預設值
  • 引數的預設值必須從右向左提供
  • 函式呼叫時使用了預設值,則後續引數必須使用預設值
  • C++中支援佔位引數,用於相容C語言中的不規範寫法