如何在 C++ 中向方法传递可选参数?
任何代码片段...
这是一个将 mode 作为可选参数传递的示例
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
NULL
表示空指针,即使它被定义为字面量 0
。它不是常量零的通用名称。对于整数类型(非指针),您应该使用数字: int mode = 0
。 - UncleBens关于默认参数使用的一个重要规则:
默认参数应该在最右端指定,一旦您指定了默认值参数,您就不能再次指定非默认参数。
例如:
int DoSomething(int x, int y = 10, int z) -----------> Not Allowed
int DoSomething(int x, int z, int y = 10) -----------> Allowed
int foo(int x, int y = 10, int z = 10)
并且只给一个可选参数 foo(1,2)
,应该怎么做呢? 我自己似乎无法让它工作。 - Gerard对于多个默认参数的情况,可能会让一些人感兴趣:
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/
myfile.h
void myfunc(int blah, int mode = 0);
myfile.cpp
void myfunc(int blah, int mode) /* mode = 0 */
{
if (mode == 0)
do_something();
else
do_something_else();
}
自从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
使用默认参数
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 )
就像没有默认值的参数一样,用逗号将它们分隔开。
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;
}
补充一下@Pramendra的答案,如果你有函数的声明和定义,在声明中需要指定默认参数。