简体   繁体   English

函数参数已在函数声明C ++中初始化

[英]Function argument already initialized in function declaration C++

So here's my question in the function declaration there is an argument and it is already initialized to a certain value. 所以这是我在函数声明中的问题,有一个参数,它已经初始化为某个值。 What are the procedures to call this function and use that default value, or is it just a way to document code, telling other programmers what you expect them to use as a value for the parameter? 调用此函数并使用该默认值的过程是什么,或者它只是一种记录代码的方法,告诉其他程序员您希望它们用作参数的值? Thank you. 谢谢。

enum File
{
    XML = 0,
    PDF = 1,
};

Char *SetSection(const File = XML);

If I understand your question correctly, simply calling SetSection with no parameters will do. 如果我正确理解你的问题,只需调用没有参数的SetSection即可。

SetSection();

The above call gets translated (for lack of a better term) to: 上述调用被翻译(缺少更好的术语):

SetSection(XML);

这意味着可以在没有参数的情况下调用该函数,在这种情况下将使用默认值XML。

In this case, File is a default argument . 在这种情况下, File默认参数 Calling SetSection() without arguments will set the File argument to the default value specified in the declaration. 不带参数调用SetSection()会将File参数设置为声明中指定的默认值。

If you call 如果你打电话

SetSection();

It will call SetSection(XML) instead. 它将调用SetSection(XML)。 This is why the optional parameters have to be at the end of all parameters. 这就是可选参数必须位于所有参数末尾的原因。 If you don't provide enough parameters, it will use the default. 如果您没有提供足够的参数,它将使用默认值。

XML is the standard parameter. XML是标准参数。 You can call it with SetSection(); 你可以用SetSection();调用它SetSection(); (But SetSection(XML) or SetSection(PDF) are valid, too). (但SetSection(XML)SetSection(PDF)也是有效的)。

What you are seeing in the declaration is a default argument value. 您在声明中看到的是默认参数值。

If you call SetSection(); 如果你调用SetSection(); it is the same as calling SetSection(XML); 它与调用SetSection(XML);

You can also call SetSelection(PDF); 您也可以调用SetSelection(PDF); or use any other valid parameter to override the default. 或使用任何其他有效参数来覆盖默认值。

You may also be seeing the result of an incremental development which started with the function having no parameter and calls to the function scattered throughout the code. 您可能还会看到增量开发的结果,该开发以函数没有参数开始,并调用分散在整个代码中的函数。 Then the alternative file type of PDF was introduced, but the prototype was changed to have a default value, which meant not having to change the existing call site. 然后引入了替代文件类型的PDF,但原型被更改为具有默认值,这意味着不必更改现有的调用站点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM