C語言不支援給函數參數指定預設值,而C++支援。
C++預設參數機制:預設參數是聲明或定義函數時為函數的參數指定一個預設值。在調用該函數時,如果沒有指定實參則采用該預設值,否則使用指定的實參。
例如:在test.c中,下面程式會編譯失敗
#include <stdio.h>
void test(int a = 1)
{
printf("a = %d\n", a);
}
int main()
{
test();
test(1);
return 0;
}
而在test.cpp中,test.cpp會編譯通過
#include <iostream>
void test(int a = 1)
{
std::cout<<"a = "<<a<<std::endl;
}
int main()
{
test();
test(1);
return 0;
}
預設參數分為:
- 半預設參數
void test(int ele1, int ele2, int ele3 = 3);
void test(int ele1, int ele2 = 2, int ele3 = 3);
- 全預設參數
void test(int ele1 = 1, int ele2, int ele3 = 3);
注:全預設參數函數會和無參數函數造成二義性。
void test();
void test(int ele1 = 1, int ele2, int ele3 = 3);
上例中:當使用不帶參方式調用test()時,編譯器無法确定是調用哪個。
預設參數注意事項:
1. 帶預設值的參數必須放在參數表的最後面,從後往前給預設值。
2. 預設參數不能同時在函數的聲明和函數定義中出現,二者隻能選其一,最好選在聲明時。
3. 預設值必須是常量或全局變量。
4. 預設參數必須通過值參或常參傳遞。