如何:使用 interior_ptr 關鍵字宣告實值類型 (C++/CLI)

interior_ptr 可與實值型別搭配使用。

重要

/clr 編譯器選項支援這項語言功能,/ZW 編譯器選項則不支援。

範例:具有實數值型別的interior_ptr

描述

下列 C++/CLI 範例會示範如何使用 interior_ptr 搭配實值型別。

代碼

// interior_ptr_value_types.cpp
// compile with: /clr
value struct V {
   V(int i) : data(i){}
   int data;
};

int main() {
   V v(1);
   System::Console::WriteLine(v.data);

   // pointing to a value type
   interior_ptr<V> pv = &v;
   pv->data = 2;

   System::Console::WriteLine(v.data);
   System::Console::WriteLine(pv->data);

   // pointing into a value type
   interior_ptr<int> pi = &v.data;
   *pi = 3;
   System::Console::WriteLine(*pi);
   System::Console::WriteLine(v.data);
   System::Console::WriteLine(pv->data);
}
1
2
2
3
3
3

範例: this 指標

描述

在實值型別中 this ,指標會評估為interior_ptr。

在實值型別的非靜態成員函式主體中, this 是 型 Vinterior_ptr<V> 別的運算式,其值是呼叫函式之物件的位址。

代碼

// interior_ptr_value_types_this.cpp
// compile with: /clr /LD
value struct V {
   int data;
   void f() {
      interior_ptr<V> pv1 = this;
      // V* pv2 = this;   error
   }
};

範例:運算子位址

描述

下列範例將示範如何使用具有靜態成員的傳址運算子。

靜態 Visual C++ 類型成員的位址會產生原生指標。 因為實值類型成員會配置在執行階段堆積上,而且可以由記憶體回收行程移動,所以靜態實值類型成員的位址是 Managed 指標。

程式碼

// interior_ptr_value_static.cpp
// compile with: /clr
using namespace System;
value struct V { int i; };

ref struct G {
   static V v = {22};
   static int i = 23;
   static String^ pS = "hello";
};

int main() {
   interior_ptr<int> p1 = &G::v.i;
   Console::WriteLine(*p1);

   interior_ptr<int> p2 = &G::i;
   Console::WriteLine(*p2);

   interior_ptr<String^> p3 = &G::pS;
   Console::WriteLine(*p3);
}
22
23
hello

另請參閱

interior_ptr (C++/CLI)