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

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.

主站蜘蛛池模板: 武隆县| 九龙坡区| 突泉县| 文昌市| 英德市| 汶川县| 封丘县| 浏阳市| 阿拉善右旗| 鄂伦春自治旗| 海宁市| 佛教| 横山县| 云安县| 扶余县| 金阳县| 文登市| 都安| 莱阳市| 澄城县| 莱芜市| 福清市| 万荣县| 海城市| 余江县| 竹溪县| 冕宁县| 洱源县| 荣昌县| 白玉县| 福泉市| 会昌县| 宁陵县| 玛纳斯县| 田林县| 凉山| 栾城县| 阳泉市| 托里县| 略阳县| 涪陵区|