141

如何将可选参数传递给 C++ 中的方法?任何代码片段...

4

8 回答 8

173

这是一个将模式作为可选参数传递的示例

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
于 2010-09-24T04:07:48.117 回答
63

关于默认参数使用的一个重要规则:
默认参数应该在最右边指定,一旦指定了默认值参数,就不能再指定非默认参数。前任:

int DoSomething(int x, int y = 10, int z) -----------> Not Allowed

int DoSomething(int x, int z, int y = 10) -----------> Allowed 
于 2010-09-24T04:10:45.307 回答
40

如果有多个默认参数,你们中的一些人可能会感兴趣:

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/

于 2016-07-14T11:43:36.930 回答
30

为了遵循此处给出的示例,但为了阐明使用头文件的语法,函数前向声明包含可选参数默认值。

我的文件.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();
}
于 2019-06-19T22:21:31.857 回答
15

使用默认参数

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 )
于 2010-09-24T04:08:37.730 回答
15

随着 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

请参阅https://en.cppreference.com/w/cpp/utility/optional

于 2020-05-04T17:32:25.700 回答
10

用逗号分隔它们,就像没有默认值的参数一样。

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
于 2010-09-24T04:05:01.920 回答
9

通常通过为参数设置默认值:

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;
}
于 2010-09-24T04:06:05.513 回答