Visual C++ .NET/Language Basics/gcnew
Содержание
Assign new value to dereferenced int
#include "stdafx.h"
using namespace System;
void main()
{
int ^y = gcnew int(100);
*y = 110;
Console::WriteLine(*y);
}
Create a handle to an int
#include "stdafx.h"
using namespace System;
void main()
{
int ^y = gcnew int(100); // create a handle to an int
Console::WriteLine(y); // print out int.
}
generic gcnew
#include "stdafx.h"
using namespace System;
generic <typename T> where T: gcnew()
T CreateInstance()
{
return gcnew T();
}
ref class MyClass
{
public:
MyClass() { }
};
int main()
{
int i = CreateInstance<int>();
MyClass^ r = CreateInstance<MyClass^>();
}
Using gcnew
#include "stdafx.h"
using namespace System;
ref class ParentClass{
public:
ParentClass() : PVal(10) {}
ParentClass(int inVal) : PVal(inVal) {}
ParentClass(const ParentClass %p) : PVal(p.PVal) {}
int PVal;
};
ref class ChildClass : public ParentClass{
public:
ChildClass () : CVal(20) {};
ChildClass (int inVal1, int inVal2) : ParentClass(inVal1), CVal(inVal2) {}
ChildClass(const ChildClass %vals) : ParentClass(vals.PVal), CVal(vals.CVal) {}
int CVal;
};
void main()
{
ChildClass ^c1 = gcnew ChildClass(5,6); // Constructor
ChildClass c2 = *c1; // Copy Constructor
c1->CVal = 12; // Change original, new unchanged
Console::WriteLine("c1=[{0}/{1}] c2=[{2}/{3}]",
c1->PVal, c1->CVal, c2.PVal, c2.CVal);
}