[英]How to pass optional arguments to a method in C++?
如何將可選的 arguments 傳遞給 C++ 中的方法? 任何代碼片段...
這是將模式作為可選參數傳遞的示例
void myfunc(int blah, int mode = 0)
{
if (mode == 0)
do_something();
else
do_something_else();
}
您可以通過兩種方式調用 myfunc 並且都有效
myfunc(10); // Mode will be set to default 0
myfunc(10, 1); // Mode will be set to 1
關於默認參數使用的重要規則:
默認參數應該在最右端指定,一旦指定了默認值參數,就不能再次指定非默認參數。 例如:
int DoSomething(int x, int y = 10, int z) -----------> Not Allowed
int DoSomething(int x, int z, int y = 10) -----------> Allowed
有些人可能會感興趣,如果有多個默認參數:
void printValues(int x=10, int y=20, int z=30)
{
std::cout << "Values: " << x << " " << y << " " << z << '\n';
}
鑒於以下函數調用:
printValues(1, 2, 3);
printValues(1, 2);
printValues(1);
printValues();
產生以下輸出:
Values: 1 2 3
Values: 1 2 30
Values: 1 20 30
Values: 10 20 30
參考: http : //www.learncpp.com/cpp-tutorial/77-default-parameters/
為了遵循此處給出的示例,但為了使用頭文件闡明語法,函數前向聲明包含可選參數默認值。
我的文件.h
void myfunc(int blah, int mode = 0);
我的文件.cpp
void myfunc(int blah, int mode) /* mode = 0 */
{
if (mode == 0)
do_something();
else
do_something_else();
}
使用默認參數
template <typename T>
void func(T a, T b = T()) {
std::cout << a << b;
}
int main()
{
func(1,4); // a = 1, b = 4
func(1); // a = 1, b = 0
std::string x = "Hello";
std::string y = "World";
func(x,y); // a = "Hello", b ="World"
func(x); // a = "Hello", b = ""
}
注意:以下格式不正確
template <typename T>
void func(T a = T(), T b )
template <typename T>
void func(T a, T b = a )
隨着 C++17 中 std::optional 的引入,您可以傳遞可選參數:
#include <iostream>
#include <string>
#include <optional>
void myfunc(const std::string& id, const std::optional<std::string>& param = std::nullopt)
{
std::cout << "id=" << id << ", param=";
if (param)
std::cout << *param << std::endl;
else
std::cout << "<parameter not set>" << std::endl;
}
int main()
{
myfunc("first");
myfunc("second" , "something");
}
輸出:
id=first param=<parameter not set>
id=second param=something
用逗號分隔它們,就像沒有默認值的參數一樣。
int func( int x = 0, int y = 0 );
func(); // doesn't pass optional parameters, defaults are used, x = 0 and y = 0
func(1, 2); // provides optional parameters, x = 1 and y = 2
通常通過為參數設置默認值:
int func(int a, int b = -1) {
std::cout << "a = " << a;
if (b != -1)
std::cout << ", b = " << b;
std::cout << "\n";
}
int main() {
func(1, 2); // prints "a=1, b=2\n"
func(3); // prints "a=3\n"
return 0;
}
Jus 添加到@Pramendra 接受的答案,如果你有 function 的聲明和定義,只需要在聲明中指定默認參數
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.