官术网_书友最值得收藏!

Default Arguments

Another feature C++ provides to make life easier for the caller when it comes to calling functions are default arguments.

Default arguments are added to a function declaration. The syntax is to add an = sign and supply the value of the default argument after the identifier of the parameter of the function. An example of this would be:

int multiply(int multiplied, int multiplier = 1);

The caller of the function can call multiply either with 1 or 2 arguments:

multiply(10); // Returns 10

multiply(10, 2); // Returns 20

When an argument with a default value is omitted, the function uses the default value instead. This is extremely convenient if there are functions with sensible defaults that callers mostly do not want to modify, except in specific cases.

Imagine a function that returns the first word of a string:

char const * firstWord(char const * string, char separator = ' ').

Most of the time, a word is separated by a whitespace character, but a function can decide whether or not it should use a different separator. The fact that a function offers the possibility to provide a separator is not forcing most callers, which simply want to use the space, to specify it.

It is a best practice to set the default arguments in the function signature declaration, and not declare them in the definition.

主站蜘蛛池模板: 石林| 萨迦县| 图木舒克市| 洪洞县| 吉水县| 平陆县| 衡山县| 大渡口区| 酉阳| 武义县| 海南省| 清涧县| 通渭县| 建昌县| 新余市| 三穗县| 彭水| 宽城| 马关县| 泸州市| 洛阳市| 衡南县| 樟树市| 南通市| 西丰县| 马龙县| 瑞昌市| 浏阳市| 长宁区| 玛曲县| 建阳市| 宁陕县| 陈巴尔虎旗| 阿瓦提县| 资源县| 右玉县| 莱州市| 琼结县| 柏乡县| 洛阳市| 珠海市|