您的位置:首页 > 编程语言 > C语言/C++

[C++/CLI编程宝典][4]第一个C++/CLI程序

2013-03-24 19:20 393 查看
一 本次通过一个简单的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工程运行,新建工程的类型如下图:



运行后如下图:



完!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: