1. 程式人生 > >21)函數的默認參數和占位參數

21)函數的默認參數和占位參數

iostream ios style 默認 我沒 ron color log ()

1)自定義函數有默認參數,可以傳參,也可以不傳參

  

 1 #include<iostream>
 2 int fun(int a=100)
 3 {
 4     printf("%d\n",a);
 5 }
 6 int main()
 7 {
 8     fun();//這種是  我沒有傳參數
 9 
10     printf("\n");
11 
12     fun(10);//這種是我傳了參數
13 
14     return 0;
15 
16 
17 }

2)你給函數的默認參數,只能從最右面開始

1 int  fun(int  a,int b=100,int c)
2 
3
//上面這中寫法是不行的 4 5 //下面的可以 6 7 int fun(int a,int b,int c=100int d=10

3)針對(2)的正確寫法的函數,我傳參時,有幾種寫法

1 fun(1020//這個是a=10,b=20,c=100,d=10
2 
3 fun(102030//這個是a=10,b=20,c=30,d=10
4 
5 fun(102030100//這個是a=10,b=20,c=30,d=100
6 
7 哈哈,在PHP中,可以
8 fun(1020,d=100)  但是在C++中,不可以這麽幹

21)函數的默認參數和占位參數