[英]How to pass optional parameter to a method in C++?
How to pass optional parameters to a method in C++ ? 如何将可选参数传递给C ++中的方法?
is there a way like in C# we can use this statement Func(identifier:value) which allow me to pass value to any parameter i want .... for example: 有没有像在C#中那样的方式,我们可以使用此语句Func(identifier:value),该语句允许我将value传递给我想要的任何参数。例如:
//C# Code
void func(int a=4,int b,int c)
{
int sum=a+b+c;
Console.Write(sum);
}
void Main(){ func(b:5,c:6);}
In C++, default arguments have to go last, so you would write: 在C ++中,默认参数必须排在最后,因此您应该编写:
void func(int b, int c, int a=4)
{
int sum = a+b+c;
std::cout << sum;
}
int main() {
func(5, 6); // b = 5, c = 6, a uses the default of 4
}
You cannot provide named parameters all the call site the way you can in C# or Python. 您不能像在C#或Python中那样为所有调用站点提供命名参数。 There is a boost library to fake support for naming parameters, but I've never used it.
有一个Boost库可以伪造对命名参数的支持,但我从未使用过。
Yes, but, short answer is that a parameter with a default value cannot precede parameters which don't get defaults. 是的,但是简短的答案是具有默认值的参数不能在没有默认值的参数之前。 So:
所以:
void func(int a=4,int b,int c) {} //doesn't work
void func(int b, int c, int a = 4){} //works
See http://en.cppreference.com/w/cpp/language/default_arguments for more information 有关更多信息,请参见http://en.cppreference.com/w/cpp/language/default_arguments
Yes, but you can only do it to the rightmost elements. 是的,但是您只能对最右边的元素执行此操作。 So you could write
void func(int a, int b, int c=4)
or void func(int a, int b=2, int c=4)
or even void func(int a=1, int b=2, int c=4)
, but not the example you gave. 因此,您可以编写
void func(int a, int b, int c=4)
或void func(int a, int b=2, int c=4)
甚至是void func(int a=1, int b=2, int c=4)
,但不是您给出的示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.