默認參數(shù)是一個自動使用的值,如果從函數(shù)調(diào)用中省略相應的實際參數(shù)。
例如,如果在my_func(int n)n中的默認值為1,則調(diào)用my_func()的函數(shù)與my_func(1)相同。
要建立默認值,請使用函數(shù)原型。
編譯器查看原型以查看函數(shù)使用多少個參數(shù)。
以下原型使用默認參數(shù)創(chuàng)建一個函數(shù)。
char * left(const char * str, int n = 1);
上面的函數(shù)返回一個char指針。
要使原始字符串不變,使用第一個參數(shù)的const限定符。
您希望n的默認值為1,因此您將該值賦值給n。
默認參數(shù)值是一個初始化值。
如果你只留下n,它的值為1,但是如果你傳遞一個參數(shù),新的值將覆蓋1。
當您使用具有參數(shù)列表的函數(shù)時,必須從右到左添加默認值。
int my_func(int n, int m = 4, int j = 5); // VALID int my_func(int n, int m = 6, int j); // INVALID int my_func(int k = 1, int m = 2, int n = 3); // VALID
// Using default arguments.
#include <iostream>
using namespace std;
// function prototype that specifies default arguments
int boxVolume( int length = 1, int width = 1, int height = 1 );
int main()
{
// no arguments--use default values for all dimensions
cout << "The default box volume is: " << boxVolume();
// specify length; default width and height
cout << "\n\nThe volume of a box with length 10,\n"
<< "width 1 and height 1 is: " << boxVolume( 10 );
// specify length and width; default height
cout << "\n\nThe volume of a box with length 10,\n"
<< "width 5 and height 1 is: " << boxVolume( 10, 5 );
// specify all arguments
cout << "\n\nThe volume of a box with length 10,\n"
<< "width 5 and height 2 is: " << boxVolume( 10, 5, 2 )
<< endl;
} // end main
// function boxVolume calculates the volume of a box
int boxVolume( int length, int width, int height )
{
return length * width * height;
}
上面的代碼生成以下結果。
以下代碼創(chuàng)建一個帶有默認參數(shù)的字符串函數(shù)。
#include <iostream>
using namespace std;
const int SIZE = 80;
char * left(const char * str, int n = 1);
int main(){
char sample[SIZE];
cout << "Enter a string:\n";
cin.get(sample,SIZE);
char *ps = left(sample, 4);
cout << ps << endl;
delete [] ps; // free old string
ps = left(sample);
cout << ps << endl;
delete [] ps; // free new string
return 0;
}
char * left(const char * str, int n){
if(n < 0)
n = 0;
char * p = new char[n+1];
int i;
for (i = 0; i < n && str[i]; i++)
p[i] = str[i]; // copy characters
while (i <= n)
p[i++] = "\0"; // set rest of string to "\0"
return p;
}
上面的代碼生成以下結果。
更多建議: