變數引數清單 (...) (C++/CLI)

這個範例顯示如何在 Visual C++ 中使用 ... 語法實作具有引數的變數數字的函式。

使用 ... 的參數必須是參數清單中的最後一個參數。

範例

9dt1588w.collapse_all(zh-tw,VS.110).gif程式碼

// 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 ));
}

9dt1588w.collapse_all(zh-tw,VS.110).gifOutput

3

程式碼範例

下列範例顯示如何從 C# 呼叫可接受變動數目的引數數目的 Visual C++ 函式。

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

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

例如,函式, f 可以從 C# 或 Visual Basic 呼叫,如同它可以接受引數的變數數字的函式。

在 C# 中,傳遞至 ParamArray 參數的引數可以依照引動過程中使用不定數目呼叫。下列程式碼範例在 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");
   }
}

f 對的呼叫中 Visual C++ 可以將初始化的陣列或可變長度的陣列。

// 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", "!!!");
}

請參閱

參考

陣列 (C++ 元件擴充功能)