定义函数时写下参数初值
c++中:
定义函数的时候,可以在函数的参数中,直接写下初始值。如果在调用此函数时,传了值,则以传入的值为准,如果没有传入此参数,则以函数中定义的值为准
例子:
#include <iostream>
#include <string>
#include <sstream>using namespace std;
//定义函数,写下函数需要的参数,同时定义初始值
void strsplit(int a = 10, bool ok = true)
{cout << "a: " << a << endl;if (ok){a += 10;cout << "a + 10 = " << a << endl;}
}int main()
{const string src = "he#is#me";char split = '#';string strTmp;istringstream iss(src);getline(iss, strTmp, split);cout << "strTmp: " << strTmp << endl;//调用函数时,没有传入参数则使用函数中的参数strsplit();sleep (2);//调用函数时,传入了参数,则使用传入的参数strsplit(5, false);return 0;
}
运行结果:
发布评论