因為常常忘記,但這功能很實用所以記下來~~
很簡單,就是在原型後面加上"= VALUE" VALUE是你定的常數,
限制是預設引數只能從右到左設定,以下源碼實現了陣列預設引數。
EX:
///////////////////////////////////////////////////////////
// args.cpp
// Generated by Code::Blocks svn build 5456
// Created on: 2009/3/31
// Original author: 天亮damody
// contry: ROC
// capability: How to use default argument
//
///////////////////////////////////////////////////////////
#include <iostream>
#include <stdlib.h>
#include <string>
using namespace std;
string hobbys[] = {"sleep","eat"};
int I_need_girlfriend(const string name = "sleep beauty",
unsigned int age = 18, string hobby[] = hobbys, unsigned int length = 1);
int main()
{
// use default argument
string hobby[] = {"sport","read"};
I_need_girlfriend("perfect girl", 20, hobby, 2);
// use default argument
string normal_hobby = "string";
I_need_girlfriend("normal girl", 20,&normal_hobby);
// not use default argument
I_need_girlfriend();
}
int I_need_girlfriend(const string name, unsigned int age, string hobby[], unsigned int
length)
{
cout << name << endl
<< "age = " << age << endl
<< "hobby = ";
for (int i = 0;i < length;i++)
{
cout << hobby[i] << ", ";
}
cout << "\b\b.\n\n";
}
留言列表