Variable number of arguments in C++?

后端 未结 17 1760
-上瘾入骨i
-上瘾入骨i 2020-11-21 23:13

How can I write a function that accepts a variable number of arguments? Is this possible, how?

17条回答
  •  甜味超标
    2020-11-21 23:38

    It's possible you want overloading or default parameters - define the same function with defaulted parameters:

    void doStuff( int a, double termstator = 1.0, bool useFlag = true )
    {
       // stuff
    }
    
    void doStuff( double std_termstator )
    {
       // assume the user always wants '1' for the a param
       return doStuff( 1, std_termstator );
    }
    

    This will allow you to call the method with one of four different calls:

    doStuff( 1 );
    doStuff( 2, 2.5 );
    doStuff( 1, 1.0, false );
    doStuff( 6.72 );
    

    ... or you could be looking for the v_args calling conventions from C.

提交回复
热议问题