How to pass optional parameters to a method in 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# 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:
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. There is a boost library to fake support for naming parameters, but I've never used it.
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
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.