0
about default arguments
I try this situation, if you start using the default parameters, then you need to add default parameters after each of the parameters, if not will be error Test(int x, int y=0, int y){} ; error Test ( int x, int y=0, int z=0){}; true But I want "z" not accept null arguments How can I quickly and easily solve this problem. ------- is these? if(z==0){ cout<<“z not accept null arguments”; return 0; } --------- Question 2: How can I run this function : test (1,,3) I just want "y" to accept null arguments.
4 Respostas
+ 1
You could overload the function like this:
int test( int x, int y, int z )
{
// Implementation here
}
int test( int x, int z )
{
return test(x, 0, z);
// When 2 arguments are given it calls the implementation with y being 0 as default
}
int main()
{
test( 1, 4, 3 );
test( 1, 3 );
}
+ 1
You can't pass void to parameters in C++, You can use default parameters instead.
But defaults go from right to left, so if you have a function with 3 parameters and want the 2nd to be default, then the 2nd and the 3rd have to be default.
Sometimes you don't want this so to work around this you overload the function to accept both 2 and 3 parameters.
I can't come up with examples in the c++ library that use this workaround, if they use this at all.
The best to void parameters you can get are probably nullptr's, but this requires you to accept pointers so this won't work when you don't use pointers.
Or just passing some kind of value that represents a null value for other types and have the function handle that.
0
in some header they also defined as such?
I've used other programming languages and can pass void parameters.
0
alright,got it thk🙏