Visual C++ .NET/Function/Function parameter

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

param array parameter

 
#include "stdafx.h"
using namespace System;
int Total( int a, ... array<int>^ varargs)
{
   int tot = a;
   for each ( int i in varargs)
   {
      tot += i;
   }
   return tot;
}
int main()
{
   int sum1 = Total(100, 200, 350);
   Console::WriteLine("First total: {0}", sum1);
   int sum2 = Total(1, 2, 3, 4, 5, 6, 7, 8);
   Console::WriteLine("Second total: {0}", sum2);
}


parameter passing

 
#include "stdafx.h"
void byvalue(int i)
{
   i += 1;
}
void byref(int& i)
{
   i += 1;
}
int main()
{
   int j = 10;
   System::Console::WriteLine("Original value: " + j);
   byvalue(j);
   System::Console::WriteLine("After byvalue: " + j);
   byref(j);
   System::Console::WriteLine("After byref: " + j);
}


pass by reference

 
#include "stdafx.h"
using namespace System;
value class Pair
{
  public:
     int x;
     int y;
};
void swap_values(Pair% pair)
{
    int temp = pair.x;
    pair.x = pair.y;
    pair.y = temp;
}
int main()
{
   Pair p;
   p.x = 5;
   p.y = 3;
   Console::WriteLine("{0} {1}", p.x, p.y);
   swap_values(p);
   Console::WriteLine("{0} {1}", p.x, p.y);
}


pass by value

 
#include "stdafx.h"
using namespace System;
ref struct R
{
   R()
   {
      val = 1;
   }
   // copy constructor
   R( R% r)
   {
      val = r.val;
   }
   property int val;
};
void f(R r_local)
{
   r_local.val = 2;
   Console::WriteLine("Within f: " + r_local.val);
}
int main()
{
    R r;
    f(r);
    Console::WriteLine("Outside f: " + r.val);
    R^ rhat = gcnew R();
    f(*rhat);  
    Console::WriteLine("Outside f: " + rhat->val);
}


Passing array as parameter

 
#include "stdafx.h"
using namespace System;
void set_to_one(int i, array<int>^ array_arg)
{
   array_arg[i] = 1;
}
int main()
{
    array<int>^ array1 = { 0, 1 };
    set_to_one(0, array1);
    Console::WriteLine(" {0} {1}", array1[0], array1[1]);
}


Passing value struct to function

 

#include "stdafx.h"
using namespace System;
value struct V
{
   int a;
   int b;
};
void f(V% v)
{
   v.a = 10;
   v.b = 20;
}
int main()
{
   V v;
   v.a = 1;
   v.b = 2;
   f(v);
   Console::WriteLine("{0} {1}", v.a, v.b);
}