執行個體解析C++/CLI的“複製”

來源:互聯網
上載者:User

C++/CLI不但支援基於堆棧的對象,同時也支援基於堆的對象;然而,如果想與其他基於CLI的語言(如C#、J#、Visual Basic)進行互操作的話,必須要清楚地知道,這些語言只支援基於堆的對象;當處於基於堆的對象環境中時,你與對象之間,永遠只有"一臂之遙",比方說,兩個給定的控制代碼h1與h2,只有在為這種控制代碼類型定義了相應的賦值操作符時,*h1 = *h2才會工作正常,而對C++/CLI之外的其他語言中的類型來說,情況可能就不是這樣了。同樣地,一個遵從CLS的機制需要建立對象的一份副本,這種機制被稱為"複製"。

使用CLI庫中的Clone函數

請看例1中的代碼,其使用了類似於向量的一個System::ArrayList類,插1是程式的輸出。

例1:

using namespace System;
using namespace System::Collections;
void PrintEntries(String^ s, ArrayList^ aList);
int main()
{
  ArrayList^ al1 = gcnew ArrayList;
  /*1*/ al1->Add("Red");
  al1->Add("Blue");
  al1->Add("Green");
  al1->Add("Yellow");
  /*2*/ PrintEntries("al1", al1);
  /*3*/ ArrayList^ al2 = static_cast<ArrayList^>(al1->Clone());
  /*4*/ PrintEntries("al2", al2);
  /*5*/ al1->Remove("Blue");
  al1->Add("Black");
  al1->RemoveAt(0);
  al1->Insert(0, "Brown");
  /*6*/ PrintEntries("al1", al1);
  /*7*/ PrintEntries("al2", al2);
}
void PrintEntries(String^ s, ArrayList^ aList)
{
  Console::Write("{0}: ", s);
  for each(Object^ o in aList)
  {
   Console::Write("\t{0}", o);
  }
  Console::WriteLine();
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.