Visual C++ .NET/Class/Operator Overload

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Operator Overload Demo

 
#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);  
}


Relational Operator Overload

 
#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);
}