介绍
这期内容当中小编将会给大家带来有关怎么在c++项目中实现一个可变参数函数,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。
<强>一、变长参数函数强>
头文件:# include & lt; stdarg.h>
函数声明
int 添加(int 计数,,…);
函数定义
int 添加(int 计数,…) { 弗吉尼亚州,va_list ; ,va_start (va,,数); ,int sum =, 0; ,for (int 小姐:=,0;,小姐:& lt;,计数;,我+ +) +=,sum va_arg (va, int); ,va_end (va); ,return 总和; }
函数调用
int 主要() { , ,cout<& lt; add (5,, 1,, 2,, 3,, 4,, 5) & lt; & lt; endl;//输出15 ,return 0; }
<强>二,C + + 11的新特性,变长参数模板。强>
边长参数模板相当于一个模板的递归展开模型,但是它不是递归的。使用的时候,要定义一个“递归”的出口,然后定义一系列的操作,操作的是以“递归”的方式进行的。
递归函数方式展开,模板推导的时候,一层层递归展开,最后到没有参数时用定义的一般函数终止。
void 测试() ,{ ,cout & lt; & lt;“测试()“,& lt; & lt;, endl; ,} ,template & lt; class T),类…,Args> ,void 测试(T 首先,,Args…, Args) ,{ ,,cout & lt; & lt;,类型id (T) . name (), & lt; & lt;,,,,, & lt; & lt;, first & lt; & lt; endl; ,,测试(args…); ,} test<, int, int, long> (1,, 2,, 3 l);//输出 int 1 int 2 long 3 测试()
嗯?第一个测试()应该是作为测试函数递归调用的结尾。再测试一下
template & lt;, class T> ,void 测试(const T , t) ,{ ,cout & lt; & lt;“测试()“& lt; & lt; t & lt; & lt;, endl; ,} ,template & lt; class T),类…,Args> ,void 测试(T 首先,,Args…, Args) ,{ ,,cout & lt; & lt;,类型id (T) . name (), & lt; & lt;,,,,, & lt; & lt;, first & lt; & lt; endl; ,,测试(args…); ,} ,//输出 int 1 int 2 测试(3)
这....好像是通过第一个测试来控制在哪里结束。
最后写一个正经的累加器:
# include & lt; iostream> # include & lt; stdarg.h> using namespace 性传播疾病; templateint 添加(const T&, t) { ,return t; } template int 添加(const T&, t, const Args&……, args), { ,return t  +,添加(args…); } int main (), { ,auto res =,添加(2,,3,,3); ,std:: cout & lt; & lt;, res & lt; & lt;, std:: endl; ,系统(“pause"); ,return 0; }//输出结果,8
上述就是小编为大家分享的怎么在c++项目中实现一个可变参数函数了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注行业资讯频道。