一 本次通過一個簡單的C++/CLI控制台程式,能使學習者有對C++/CLI程式有個個大概的印象,同時引出一些基本的概念和關鍵字。下面是程式碼:
#include <iostream>
#include <string>
// 1 ISOC++
public class NativeClass
{
public:
NativeClass(std::string str)
{
m_str = str;
std::cout << "ISOC++ 本地類型構造!" << std::endl;
}
~NativeClass()
{
std::cout << "ISOC++ 本地類型析構!" << std::endl << std::endl;
}
void Print()
{
std::cout << m_str << std::endl;
}
private:
std::string m_str;
};
// 2 C++/CLI
value struct ValueStruct
{
System::String^ m_str;
ValueStruct(System::String^ str)
{
m_str = str;
System::Console::WriteLine("託管value實值型別構造!");
}
// 不能有解構函式
//~ValueStruct()
//{
// System::Console::WriteLine("託管value實值型別析構!");
//}
void Print()
{
System::Console::WriteLine(m_str);
}
};
// 3 C++/CLI
ref class RefClass
{
public:
RefClass(System::String^ str)
{
m_str = str;
System::Console::WriteLine();
System::Console::WriteLine("託管ref參考型別構造!");
}
~RefClass()
{
System::Console::WriteLine("託管ref參考型別析構!");
System::Console::WriteLine();
}
void Print()
{
StartPrint();
System::Console::WriteLine(m_str);
EndPrint();
}
// 屬性property,委託delegate和事件event
property System::String^ Str
{
System::String^ get() { return m_str; }
void set(System::String^ str) { m_str = str; }
}
delegate void PrintDelegate(void);
event PrintDelegate^ StartPrint;
event PrintDelegate^ EndPrint;
private:
System::String^ m_str;
};
void StartPrint()
{
System::Console::WriteLine("Print開始事件,馬上開始Print函數調用!");
}
void EndPrint()
{
System::Console::WriteLine("Print結束事件,Print函數調用結束!");
}
void main()
{
NativeClass* pNC = new NativeClass("你好,我是ISOC++本地類型!");
pNC->Print();
delete pNC;
ValueStruct vs("你好,我是託管value實值型別!");
vs.Print();
RefClass^ hRC = gcnew RefClass("你好,我是託管ref參考型別!");
hRC->StartPrint += gcnew RefClass::PrintDelegate(StartPrint);
hRC->EndPrint += gcnew RefClass::PrintDelegate(EndPrint);
hRC->Print();
hRC->Str = "你好,我是託管ref參考型別!現在正通過property屬性修改成員feild欄位!";
hRC->Print();
delete hRC;
}
二 下面逐步分析代碼和簡單解釋一些新關鍵字和新名詞:
1)類型NativeClass是ISOC++的類型,使用是使用new構造,使用完後然後delete。
2)類型ValueStruct為C++/CLI新的託管value實值型別,直接使用,不需要new或gcnew,value實值型別不能有解構函式,因此也不必delete,value實值型別被分配在棧上。
3)類型RefClass為C++/CLI的新的託管ref參考型別,使用gcnew構造,用完後delete,也可以不delete,因為實際上Ref類型是的執行個體是分配在託管堆上的,記憶體由CLR的垃圾收集器來管理。
4)在RefClass我們可以看到C++/CLI中引入了新的關鍵字property屬性,delegate委託和event事件。
三 上面的代碼可以使用VS2008建立CLR的C++的console工程運行,建立工程的類型如:
運行後如:
完!