如何将可选参数传递给 C++ 中的方法?
如何将可选参数传递给 C++ 中的方法? 任何代码片段...
How to pass optional arguments to a method in C++ ?
Any code snippet...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
如何将可选参数传递给 C++ 中的方法? 任何代码片段...
How to pass optional arguments to a method in C++ ?
Any code snippet...
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(9)
这是将模式作为可选参数传递的示例,
您可以通过两种方式调用 myfunc,并且两者都是有效的
Here is an example of passing mode as optional parameter
you can call myfunc in both ways and both are valid
关于默认参数使用的重要规则:
默认参数应该指定在最右端,一旦指定了默认值参数就不能再次指定非默认参数。
前任:
An important rule with respect to default parameter usage:
Default parameters should be specified at right most end, once you specify a default value parameter you cannot specify non default parameter again.
ex:
为了遵循此处给出的示例,但为了澄清使用头文件的语法,函数前向声明包含可选参数默认值。
myfile.h
myfile.cpp
To follow the example given here, but to clarify syntax with the use of header files, the function forward declaration contains the optional argument default value.
myfile.h
myfile.cpp
你们中的一些人可能会感兴趣,在有多个默认参数的情况下:
给出以下函数调用:
产生以下输出:
参考: http://www.learncpp.com/cpp-tutorial/77-default-parameters/
It might be interesting to some of you that in case of multiple default parameters:
Given the following function calls:
The following output is produced:
Reference: http://www.learncpp.com/cpp-tutorial/77-default-parameters/
随着 C++17 中 std::Optional 的引入,您可以传递可选参数:
输出:
参见 https://en.cppreference.com/w/cpp/utility/可选
With the introduction of std::optional in C++17 you can pass optional arguments:
Output:
See https://en.cppreference.com/w/cpp/utility/optional
使用默认参数
注意:以下格式不正确
Use default parameters
Note : The following are ill-formed
用逗号分隔它们,就像没有默认值的参数一样。
With commas separating them, just like parameters without default values.
通常通过设置参数的默认值:
Typically by setting a default value for a parameter:
只需添加 @Pramendra 的接受的 ans ,如果您有函数的声明和定义,则仅在声明中需要指定默认参数
Jus adding to accepted ans of @Pramendra , If you have declaration and definition of function, only in declaration the default param need to be specified