码迷,mamicode.com
首页 > 其他好文 > 详细

C ++ / CLI 语法

时间:2020-05-16 12:41:37      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:system   ast   处理   code   地址   lib   指定   sub   print   

1、Handles and Pointers

您可能已经在C ++ / CLI代码中看到标点符号“ ^”并对此感到疑惑。如您所知,在C ++中,表示指针,在C ++ / CLI中,表示句柄。现在,“ *”指定驻留在CRT堆上的本机指针,而句柄则指定“安全指针”并驻留在托管堆上。可以将这些句柄视为引用,并且与本机指针不同,如果未正确删除它们,它们将不会引起内存泄漏,因为GC会处理这些问题,并且它们没有固定的内存地址,因此将在执行过程中移动。

要创建某个特定类或值类型的新引用,我们必须使用“ gcnew”关键字进行分配;例如:

System::Object ^x = gcnew System::Object();

 

值得注意的是,nullptr关键字“ ”表示空引用。除了标点符号“ ^”外,我们还有百分比“ %”代表跟踪参考;我想引用ECMA-372:

N* pn = new N;   // allocate on native heap
N& rn = *pn;     // bind ordinary reference to native object
R^ hr = gcnew R; // allocate on CLI heap
R% rr = *hr;     // bind tracking reference to gc-lvalue

 

在一般情况下,加标点%^因为加标点&*

2、Classes and UDTs (user defined types)

注意:在public后面跟着ref关键字

public ref class MyClass
{
private:
public:
  MyClass()
  {

  }
}
#using <mscorlib.dll>

using namespace System;

public ref class MyNamesSplitterClass
{
private:
  System::String ^_FName, ^_LName;
public:
  MyNamesSplitterClass(System::String ^FullName)
  {
    int pos = FullName->IndexOf(" ");
    if (pos < 0)
      throw gcnew System::Exception("Invalid full name!");
    _FName = FullName->Substring(0, pos);
    _LName = FullName->Substring(pos+1, FullName->Length - pos -1);
  }

  void Print()
  {
    Console::WriteLine("First name: {0}\nLastName: {1}", _FName, _LName);
  }
};

int main(array<System::String ^> ^args)
{
  // local copy

  MyNamesSplitterClass s("John Doe");
  s.Print();

  // managed heap

  MyNamesSplitterClass ^ms = gcnew MyNamesSplitterClass("Managed C++");
  ms->Print();

  return 0;
}

Value types

 

C ++ / CLI 语法

标签:system   ast   处理   code   地址   lib   指定   sub   print   

原文地址:https://www.cnblogs.com/jshchg/p/12899793.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!