Condividi tramite


... (Variable Argument Lists)

This example shows how functions with a variable number of arguments can be implemented in Visual C++ using the ... syntax.

The parameter that uses ... must be the last parameter in the parameter list.

Example

Code

// mcppv2_paramarray.cpp
// compile with: /clr
using namespace System;
double average( ... array<Int32>^ arr ) {
   int i = arr->GetLength(0);
   double answer = 0.0;

   for (int j = 0 ; j < i ; j++)
      answer += arr[j];

   return answer / i;
}

int main() {
   Console::WriteLine("{0}", average( 1, 2, 3, 6 ));
}

Output

3

Legacy Code Example

The following example shows how to call a Visual C++ function that takes a variable number of arguments from C#.

// mcppv2_paramarray2.cpp
// compile with: /clr:safe /LD
using namespace System;

public ref class C {
public: 
   void f( ... array<String^>^ a ) {}
};

The function f can be called from C# or Visual Basic, for example, as though it were a function that can take a variable number of arguments.

In C#, an argument passed to a ParamArray parameter can be called with a variable number of arguments. The following code sample is in C#.

// mcppv2_paramarray3.cs
// compile with: /r:mcppv2_paramarray2.dll
// a C# program

public class X {
   public static void Main() {
      // Visual C# will generate a String array to match the 
      // ParamArray attribute
      C myc = new C();
      myc.f("hello", "there", "world");
   }
}

A call to f in Visual C++ can pass an initialized array as well as a variable-length array:

// mcpp_paramarray4.cpp
// compile with: /clr
using namespace System;

public ref class C {
public: 
   void f( ... array<String^>^ a ) {}
};

int main() {
   C ^ myc = gcnew C();
   myc->f("hello", "world", "!!!");
}

See Also

Reference

array (Visual C++)