Operator Overload Demo : Operator Overload « Class « Visual C++ .NET

Home
Visual C++ .NET
1.2D
2.Class
3.Collections
4.Data Type
5.Database ADO.net
6.Delegate
7.Development
8.File Directory
9.Function
10.Generics
11.GUI Form
12.Language Basics
13.Network
14.Reflection
15.Security
16.Statement
17.Structure
18.Thread
19.XML
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Visual C++ .NET » Class » Operator Overload 
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->i1;
                     
        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);  
}  

   
  
Related examples in the same category
1.Relational Operator Overload
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.