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.

4th Dec 2017, 1:16 PM
HE HUALIANG
HE HUALIANG - avatar
4 Answers
+ 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 ); }
4th Dec 2017, 1:38 PM
Dennis
Dennis - avatar
+ 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.
4th Dec 2017, 2:11 PM
Dennis
Dennis - avatar
0
in some header they also defined as suchļ¼Ÿ I've used other programming languages ā€‹ā€‹and can pass void parameters.
4th Dec 2017, 1:53 PM
HE HUALIANG
HE HUALIANG - avatar
0
alrightļ¼Œgot it thkšŸ™
4th Dec 2017, 2:18 PM
HE HUALIANG
HE HUALIANG - avatar