zoukankan      html  css  js  c++  java
  • C/C++中可变参数函数的实现

    在C语言的stdarg.h头文件中提供了三个函数va_start, va_end,va_arg和一个类型va_list。利用它们,我们可以很容易实现一个可变参数的函数。首先简单介绍一下这三个函数。

    假设现在有一个名为f的函数,其函数定义为:

    void f(int a, int b, ...)

    那么,在函数的内部,为了获得这些可变参数,就需要利用到va_start、va_arg和va_end三个函数。

    va_list类型的变量可以用于存储可变类型的变量,用它可以对可变变量进行遍历;

     va_list ap

    在使用ap之前,必须调用va_start使得ap和可变参数进行关联;

    va_start(ap, b);

    va_start的第二个参数是函数参数列表中最后一个非可变参数的参数;

    然后就可以调用va_arg对参数进行访问了;

    type va_arg( ap, type);

    在变量处理完成之后,程序结束之前,应该调用va_end一次;

    void va_end(ap);
    下面的程序展示了一种可变参数函数和CString::FormatV函数联合使用的技术。该技术在VC++编程中被广泛的使用:

    #include <iostream> #include <cstring> #include <string.h> #include <atltime.h> usingnamespace::std; void WriteLogEntry(LPCTSTR pstrFormat, ...) {   CTime timeWrite;   timeWrite = CTime::GetCurrentTime();   CString str = timeWrite.Format(_T("%d %b %y %H:%M:%S - "));   ATLTRACE(str);   va_list args;   va_start(args, pstrFormat); str.FormatV(pstrFormat, args);   ATLTRACE(str);   return; } int main() {   WriteLogEntry(_T("Start Program! "));   WriteLogEntry(_T("Program has execute %d lines! "),201);   WriteLogEntry(_T("error %d occured at %d line! "),1170, 400);   WriteLogEntry(_T("Program Abouted!")); }
     
  • 相关阅读:
    [leetCode]127. 单词接龙
    [leetCode]450. 删除二叉搜索树中的节点
    [leetCode]701. 二叉搜索树中的插入操作
    [leetCode]235. 二叉搜索树的最近公共祖先
    [leetCode]501. 二叉搜索树中的众数
    $Abstract^2 Interpretation$
    图说 Python 内存管理
    Python 解释器初探
    幸福之路
    Spark编程基础
  • 原文地址:https://www.cnblogs.com/liaocheng/p/4243693.html
Copyright © 2011-2022 走看看