Visual C++ .NET/Class/Operator Overload
Operator Overload Demo
<source lang="csharp">
- include "stdafx.h"
using namespace System; ref class MyClass{ public:
MyClass() : i(0) {} MyClass(int x) : i(x) {} // x != y static bool operator !=(const MyClass ^lhs, const MyClass ^rhs) { return lhs->i != rhs->i; } // x * y static MyClass^ operator *(const MyClass ^lhs, const MyClass ^rhs) { MyClass^ ret = gcnew MyClass(); ret->i = lhs->i * rhs->i; return ret; } // x *= y static void operator *=(MyClass ^lhs, const MyClass ^rhs) { lhs->i *= rhs->i; } // -x static MyClass^ operator -(const MyClass ^lhs) { MyClass^ ret = gcnew MyClass(); ret->i = -(lhs->i); return ret; } // ++x and x++ static MyClass^ operator ++(const MyClass ^lhs) { MyClass^ ret = gcnew MyClass(); ret->i = (lhs->i) + 1; return ret; } virtual String ^ ToString() override { return i.ToString(); }
private:
int i;
}; void main() {
MyClass ^op1 = gcnew MyClass(3); MyClass ^op2 = gcnew MyClass(5); MyClass ^op3 = gcnew MyClass(15); if ( op1 * op2 != op3) Console::WriteLine("not Equal"); else Console::WriteLine("Equal"); op1 *= op2; Console::WriteLine(op1); Console::WriteLine(++op1); Console::WriteLine(op1++); Console::WriteLine(-op1); Console::WriteLine(op1);
}
</source>
Relational Operator Overload
<source lang="csharp">
- include "stdafx.h"
using namespace System; ref class Number { public:
Number(int x) : i(x) {} static bool operator >(Number^ n, int v) // maps to operator > { return n->i > v; } static bool operator >(int v, Number^ n) // maps to operator > { return v > n->i; } virtual String ^ ToString() override { return i.ToString(); }
private:
int i;
};
int main() {
Number^ n = gcnew Number(5); if ( n > 6 ) Console::WriteLine("{0} Greater than 6", n); else Console::WriteLine("{0} Less than or Equal 6", n); if ( 6 > n ) Console::WriteLine("6 Greater than {0}", n); else Console::WriteLine("6 Less than or Equal {0}", n);
}
</source>