ユーザー定義の演算子 (C++/CLI)

マネージド型のユーザー定義演算子は、静的メンバーまたはインスタンス メンバーとして、またはグローバル スコープで許可されます。 ただし、Visual C++ 以外の言語で記述されたクライアントがメタデータを通じてアクセスできるのは、静的演算子だけです。

参照型で、ユーザー定義の静的演算子のパラメーターの 1 つは、次のいずれかである必要があります。

  • 外側の型のインスタンスに対するハンドル (type ^)。

  • 外側の型のインスタンスへのハンドルへの参照型間接参照 (type^>または type^%) です。

値の型で、ユーザー定義の静的演算子のパラメーターの 1 つは、次のいずれかである必要があります。

  • 外側の値の型と同じ型。

  • 外側の型へのポインター型の間接参照 (type^)。

  • 外側の型への参照型間接参照 (type% または > type)。

  • ハンドルへの参照型間接参照 (type^% または type^>)。

次の演算子を定義できます。

演算子 単項形式または 2 項形式
! 単項
!= バイナリ
% バイナリ
& 単項演算子および 2 項演算子
&& バイナリ
* 単項演算子および 2 項演算子
+ 単項演算子および 2 項演算子
++ 単項
, バイナリ
- 単項演算子および 2 項演算子
-- 単項
-> 単項
/ バイナリ
< バイナリ
<< バイナリ
<= バイナリ
= バイナリ
== バイナリ
> バイナリ
>= バイナリ
>> バイナリ
^ バイナリ
false 単項
true 単項
| バイナリ
|| バイナリ
~ 単項

例: ユーザー定義の演算子

// mcppv2_user-defined_operators.cpp
// compile with: /clr
using namespace System;
public ref struct X {
   X(int i) : m_i(i) {}
   X() {}

   int m_i;

   // static, binary, user-defined operator
   static X ^ operator + (X^ me, int i) {
      return (gcnew X(me -> m_i + i));
   }

   // instance, binary, user-defined operator
   X^ operator -( int i ) {
      return gcnew X(this->m_i - i);
   }

   // instance, unary, user-defined pre-increment operator
   X^ operator ++() {
      return gcnew X(this->m_i++);
   }

   // instance, unary, user-defined post-increment operator
   X^ operator ++(int i) {
      return gcnew X(this->m_i++);
   }

   // static, unary user-defined pre- and post-increment operator
   static X^ operator-- (X^ me) {
      return (gcnew X(me -> m_i - 1));
   }
};

int main() {
   X ^hX = gcnew X(-5);
   System::Console::WriteLine(hX -> m_i);

   hX = hX + 1;
   System::Console::WriteLine(hX -> m_i);

   hX = hX - (-1);
   System::Console::WriteLine(hX -> m_i);

   ++hX;
   System::Console::WriteLine(hX -> m_i);

   hX++;
   System::Console::WriteLine(hX -> m_i);

   hX--;
   System::Console::WriteLine(hX -> m_i);

   --hX;
   System::Console::WriteLine(hX -> m_i);
}
-5
-4
-3
-2
-1
-2
-3

例: 複合演算子

次のサンプルは複合演算子を示しています。/clr を使ってコンパイルする場合にのみ使用できます。 複合演算子は、2 項演算子の代入形式を作成します (定義されていない場合)。代入演算子の左辺は CLR 型を持ちます。

// mcppv2_user-defined_operators_2.cpp
// compile with: /clr
ref struct A {
   A(int n) : m_n(n) {};
   static A^ operator + (A^ r1, A^ r2) {
      return gcnew A( r1->m_n + r2->m_n);
   };
   int m_n;
};

int main() {
   A^ a1 = gcnew A(10);
   A^ a2 = gcnew A(20);

   a1 += a2;   // a1 = a1 + a2   += not defined in source
   System::Console::WriteLine(a1->m_n);
}
30

関連項目

クラスと構造体