📄 vararg.html
字号:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<link rel="stylesheet" href="css/stdlayout.css" type="text/css">
<link rel="stylesheet" href="css/print.css" type="text/css">
<meta content="text/html; charset=gb2312" http-equiv="content-type">
<title>不定长度引数(Variable-length argument)</title>
</head>
<body>
<h3><a href="http://caterpillar.onlyfun.net/GossipCN/index.html">From
Gossip@caterpillar</a></h3>
<h1><a href="CppGossip.html">C++
Gossip: 不定长度引数(Variable-length argument)</a></h1>
在定义函式时,有时我们并无法事先得知要传递的参数个数,这边介绍不定长度引数(Variable-length
argument)的使用为了要使用不定长度引数,您必须含入cstdarg表头档案:<br>
<div style="margin-left: 40px;"><span style="font-weight: bold; font-family: Courier New,Courier,monospace;">#include <cstdarg></span><br>
</div>
<br>
不定长度引数使用几个识别字来建立不定长度引数: <br>
<ul>
<li>va_list</li>
</ul>
<div style="margin-left: 40px;">一个特殊的型态(type),在va_start、va_arg与va_end三个巨
集(macro)时当作参数使用。 </div>
<ul>
<li>va_start</li>
</ul>
<div style="margin-left: 40px;">启始不定长度引数的巨集。 </div>
<ul>
<li>va_arg</li>
</ul>
<div style="margin-left: 40px;">读取不定长度引数的巨集。 </div>
<ul>
<li>va_end</li>
</ul>
<div style="margin-left: 40px;">终止不定长度引数的巨集。 <br>
</div>
<br>
在宣告不定长度引数时,您在函式定义时使用 ... 表示将使用不定长度引数,而之前必须告知将传递几个不定长度引数,例如: <br>
<div style="margin-left: 40px; font-family: Courier New,Courier,monospace;"><span style="font-weight: bold;">void foo(int, ...);</span><br>
</div>
<br>
在使用va_arg巨集取出引数内容时,您必须指定将以何种资料型态取出,例如:<br>
<div style="margin-left: 40px;"><span style="font-weight: bold; font-family: Courier New,Courier,monospace;">va_arg(num_list,
double);</span><br>
</div>
<br>
下面这个程式示范如何使用不定长度引数:<br>
<br>
<pre>#include <iostream> <br>#include <cstdarg> <br>using namespace std; <br><br>void foo(int, ...); <br><br>int main() { <br> double x = 1.1, y = 2.1, z = 3.9; <br> double a = 0.1, b = 0.2, c = 0.3; <br><br> cout << "三个参数:" << endl; <br> foo(3, x, y, z); <br><br> cout << "六个参数:" << endl; <br> foo(6, x, y, z, a, b, c); <br><br> return 0; <br>} <br><br>void foo(int i, ...) { <br> double tmp; <br> va_list num_list; <br><br> va_start(num_list, i); <br><br> for(int j = 0; j < i; j++) <br> cout << va_arg(num_list, double) << endl; <br><br> va_end(num_list); <br>}</pre>
<span class="postbody"><br>
执行结果:</span><br>
<table style="text-align: left; width: 100%;" border="0" cellpadding="2" cellspacing="2">
<tbody>
<tr>
<td style="background-color: rgb(0, 0, 0);"><small><span style="color: rgb(255, 255, 255);">三个参数:<br>
1.1<br>
2.1<br>
3.9<br>
六个参数:<br>
1.1<br>
2.1<br>
3.9<br>
0.1<br>
0.2<br>
0.3</span></small><span style="color: rgb(255, 255, 255);"><br>
</span></td>
</tr>
</tbody>
</table>
<br>
<br>
</body>
</html>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -