本筆記主要包含以下的內容:
1.如何在VC++2005或者2008中開啟CLR支援2.一個簡單的Hello World程式3.參考型別與實值型別4.常見CLI類型的定義5.CLI中的數組(CLI::array)6.統一類型的系統(System Unification)1.如何在VC++2005或者2008中開啟CLR支援 在當前的解決方案瀏覽器中選擇解決方案,按右鍵,選擇Property,在彈出的對話方塊的Configuration Properties的General菜單下選擇Common Language Runtime Support中選擇Common Language Runtime Support (/clr)選項,就可以正常使用.Net的內容了2.一個簡單的Hello World程式using namespace System
int main()
{
System::Console::WriteLine("hello, world");
}3.參考型別與實值型別using namespace System;
ref class Class1
{
public:
int value;
Class1()
{
value = 0;
}
};
int main()
{
int val1 = 0;
int val2 = val1;
val2 = 123;
Class1^ ref1 = gcnew Class1;
Class1^ ref2 = ref1;
ref2->value = 123;
Console::WriteLine("Values: {0},{1}",val1,val2);
Console::WriteLine("Refs: {0},{1}",ref1->value,ref2->value);
}注: 1) ^符號表示該類型為託管類型 2)gcnew與new的區別在與,gcnew是在託管堆上建立對象,可以實現自動的記憶體回收 3)ref代表該類型為託管的參考型別.4.常見CLI類型的定義public enum class Color
{
Red, Blue, Green
};
public value struct Point
{
int x, y;
};
public interface class IBase
{
void F();
};
public interface class IDerived: IBase
{
void G();
};
public ref class A
{
protected:
virtual void H()
{
Console::WriteLine("A.H");
}
};
public ref class B : A, IDerived
{
public:
virtual void F()
{
}
virtual void G()
{
}
protected:
virtual void H() override
{
}
};
public delegate void MyDelegate();包含了常見的類型的定義5.CLI中的數組(CLI:array)using namespace System;
int main()
{
array<int>^ arr1D = gcnew array<int>(4){10,42,30,12};
Console::Write("The {0} elements are:", arr1D->Length);
for (int i = 0; i < arr1D.Length; i ++)
{
Console::Write("{0,3}", i);
}
Console::WriteLine();
array<int, 3>^ arr3D = gcnew array<int, 3>(10,20,30);
}注: 1)array<int>^表示這是託管的數組 2)array可以是多維的數組,維度在array的建立的時候指定,如arr3D就是一個10*20*30的數組6.統一類型的系統using namespace System;
int main()
{
Console::WriteLine((3).ToString());
int i = 123;
Object^ o = i; //boxing
int j = safe_cast<int>(o); //unboxing
Console::WriteLine("{0}",j);
}注: 在java或者c#中,都是採用同一類型的系統,即所有的類型都是整合自Object類型.而傳統的C++不是這樣,在CLI中,所有的類型都是整合自System::Object. 在上面程式中,數字3也具有ToString()方法. 另外一點就是裝箱和拆箱的操作,在CLI中可以直接把實值型別賦值給參考型別.叫做裝箱操作,同樣,調用safe_cast方法可以完成參考型別到實值型別的轉換,成為裝箱操作.這些操作都是比較費時的轉載請註明出處,如果有問題歡迎指教