【C++】預設引數
阿新 • • 發佈:2018-12-21
-
概念:
預設引數是宣告或定義函式時為函式的引數指定一個預設值。在呼叫該函式時,如果沒有指定實參則採用該預設值,否則使用指定的實參。
#include <iostream>
using namespace std;
using std::cout;
using std::endl;
void TestFunc(int a = 0)//預設引數
{
std::cout << a << std::endl;
}
int main()
{
TestFunc();//不傳引數時,就使用預設的
TestFunc(10);//傳參時,使用指定的實參
}
分析:此時輸出結果是 0
-
分類:
- 1.全預設引數(所有引數全預設)
void TestFunc(int a = 10,int b = 20,int c=30)//預設引數 { std::cout << "a= "<< a<<std::endl; std::cout << "b= " << a << std::endl; std::cout << "c= " << a << std::endl; } int main() { TestFunc();//輸出結果為:10 20 30,都是預設值 TestFunc(1);//1 20 30 TestFunc(1,2);//1 2 30 TestFunc(1,2,3);//1 2 3 }
分析:上面就是全預設的四種用法。全預設的好處就是呼叫函式更多樣化,如果你不想傳參,就可以考慮用預設,如果是全預設,可以傳1個引數,2個引數,3個引數,都不傳引數也可以。
- 2.半預設引數(預設部分引數)
void TestFunc(int a ,int b = 20,int c=30)//預設兩個引數 { std::cout << "a= "<< a<<std::endl; std::cout << "b= " << a << std::endl; std::cout << "c= " << a << std::endl; } int main() { TestFunc(1); TestFunc(1,2); TestFunc(1,2,3); }
或
void TestFunc(int a ,int b,int c=30)//預設一個引數
{
std::cout << "a= "<< a<<std::endl;
std::cout << "b= " << a << std::endl;
std::cout << "c= " << a << std::endl;
}
int main()
{
TestFunc(1,2);
}
像這樣預設,是不行的:
void TestFunc(int a =10,int b ,int c=30)
這樣預設有一個歧義,如果傳兩個引數,不知道是傳給前兩個還是後兩個,難以明確。這就要求預設引數必須連續,並且得從右往左預設,半預設只能預設右邊的。
-
注意事項:
1.半預設引數必須從右往左依次來給出,不能間隔著給
2.預設引數不能在函式宣告和定義中同時出現
//a.h
void TestFunc(int a = 10);
// a.c
void TestFunc(int a = 20)
注意:如果宣告與定義位置同時出現,恰巧兩個位置提供的值不同,那編譯器就無法確定到底該用那個預設值。一般是在宣告的時候出現,定義的時候不用給。也可以單獨出現在定義中。
3.預設值必須是常量或者全域性變數
4. C語言不支援預設引數(編譯器不支援),這也是C語言和c++的一個區別吧!