可变参数的使用(C++和C#实现)
//C++ 中的可变参数使用
#include <stdio.h>
#include <stdarg.h>
int OpenFileArray(FILE ***array, char *mode, char *filename, ...)
{
char *pName = NULL;
int nrFiles = 0;
int arrayIndex = 0 ;
if (filename == NULL) {
return 0;
}
//在参数表中创建一个索引使用的typedef
va_list listIndex;
//在参数表中初始化第一个参数索引的宏
va_start(listIndex, filename );
do {
nrFiles++;
//得到参数表中下一参数的宏
pName = va_arg(listIndex, char *);
} while (pName != NULL);
*array = new FILE*[nrFiles + 1];
//open files
pName = filename;
va_start(listIndex, filename);
do {
if (!((*array)[arrayIndex++] = fopen(pName, mode ))) {
(*array)[arrayIndex - 1] = NULL;
return 0;
}
printf("Had open file : %s\n" , pName);
pName = va_arg(listIndex, char *);
} while (pName != NULL); //有问题
(*array)[arrayIndex ] = NULL;
return 1;
}
void main(void )
{
FILE **array;
int fp = OpenFileArray(&array, "r", "1.txt", "2.txt", "3.txt" );
if (fp == 1) {
printf ("\nopen file successfully!\n");
}
//close the files
int i = 0;
while (array[i] != NULL) {
fclose(array [i++]);
}
delete []array;
}
//C#中的可变参数使用
//如果不用params 关键字,则参数调用的时候需要使用 new object[] {arg1, arg2}
class Program
{
public static int SumWithVariableParams(params int[] args)
{
int sum = 0;
for (int i = 0; i < args.Length; i++)
{
sum += args[i];
}
return sum;
}
static void Main(string [] args)
{
System.Console.WriteLine("sum(1, 2, 3, 4, 5) = " + (SumWithVariableParams( 1, 2, 3, 4, 5)).ToString());
System.Console.WriteLine("sum(33, 22) = " + (SumWithVariableParams(33 , 22)).ToString());
System.Console.ReadLine();
}
}
没有评论:
发表评论