c++之带默认形参值的函数
先來(lái)個(gè)例子:
1 #include <iostream> 2 3 using namespace std; 4 5 int sub(int x=8,int y=3){ 6 return x+y; 7 } 8 9 int main(){ 10 //freopen("D:\\input.in","r",stdin); 11 //freopen("D:\\output.out","w",stdout); 12 cout<<sub(20,15)<<endl;//35 13 cout<<sub(10)<<endl;//13 14 cout<<sub()<<endl;//11 15 return 0; 16 }需要注意的地方:
1.若函數(shù)具有多個(gè)形參,則默認(rèn)形參值必須自右向左連續(xù)地定義,并且在一個(gè)默認(rèn)形參值的右邊不能有未指定默認(rèn)值的參數(shù)。這是由于c++語(yǔ)言在函數(shù)調(diào)用時(shí)參數(shù)是自右向左入棧這一約定決定的。
eg:int f(int a, float b=5.0, char c='c');
2.在調(diào)用一個(gè)函數(shù)時(shí),如果省去了某個(gè)實(shí)參,則直到最右端的所有實(shí)參都得省去(當(dāng)然,與其對(duì)應(yīng)的形參要有默認(rèn)值)。
eg:int f(int a, float b=5.0, char c='c', int d=10); ? ? ? ? f(9,4.5) <=> f(9,4.5,'c',10).
3.默認(rèn)形參值的說(shuō)明必須出現(xiàn)在函數(shù)調(diào)用之前。而且,如果存在函數(shù)原型,則形參的默認(rèn)值應(yīng)在函數(shù)原型中指定;否則在函數(shù)定義中指定。另外,若函數(shù)原型中已給出了形參的默認(rèn)值,則在函數(shù)定義中不得重復(fù)指定,即使所指定的默認(rèn)值完全相同也不行。
eg:
1 #include <iostream> 2 3 using namespace std; 4 5 int sub(int x=8,int y=3); 6 7 int main(){ 8 //freopen("D:\\input.in","r",stdin); 9 //freopen("D:\\output.out","w",stdout); 10 cout<<sub(20,15)<<endl;//35 11 cout<<sub(10)<<endl;//13 12 cout<<sub()<<endl;//11 13 return 0; 14 } 15 int sub(int x,int y){ 16 return x+y; 17 }4.在同一個(gè)作用域,一旦定義了默認(rèn)形參值,就不能再定義它。
5.如果幾個(gè)函數(shù)說(shuō)明出現(xiàn)在不同的作用域內(nèi),則允許分別為它們提供不同的默認(rèn)形參值。
eg:
1 #include <iostream> 2 3 using namespace std; 4 5 int sub(int x=8,int y=3); 6 7 int main(){ 8 //freopen("D:\\input.in","r",stdin); 9 //freopen("D:\\output.out","w",stdout); 10 int sub(int x=0,int y=0); 11 cout<<sub()<<endl; 12 return 0; 13 }6.對(duì)形參默認(rèn)值的指定可以是初始化表達(dá)式,甚至可以包含函數(shù)調(diào)用。
eg:int f(int a, float b=5.0, char c='c', int d=sub(20,15));
7. 在函數(shù)原型給出了形參的默認(rèn)值時(shí),形參名可以省略。
eg:int f(int, float=5.0, char='c', int=sub(20,15));
轉(zhuǎn)載于:https://www.cnblogs.com/jiu0821/p/4750316.html
總結(jié)
以上是生活随笔為你收集整理的c++之带默认形参值的函数的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 系统优化之旅
- 下一篇: s3c2440移植MQTT